我有一个用Knockout.js创建的表单.当用户按下提交按钮时,我将视图模型转换回模型并尝试提交给服务器.我试过了:
ko.utils.postJson(location.href,ko.toJSON(viewModel));
但是当它撞到服务器时,该对象是空白的.我切换到这段代码:
$.ajax({ url: location.href,type: "POST",data: ko.toJSON(viewModel),datatype: "json",contentType: "application/json charset=utf-8",success: function (data) { alert("success"); },error: function (data) { alert("error"); } });
这会将数据传输到服务器,并在其中包含正确的数据.
但我想要的是提交数据,以便我的控制器可以重定向到正确的视图.有什么建议么?
解决方法
Steve Sanderson有一个较旧的示例,它演示了如何在控制器操作中正确绑定提交的JSON数据:
http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/
它的要点是他创建了一个名为“FromJson”的属性,如下所示:
public class FromJsonAttribute : CustomModelBinderAttribute { private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer(); public override IModelBinder GetBinder() { return new JsonModelBinder(); } private class JsonModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName]; if (string.IsNullOrEmpty(stringified)) return null; return serializer.Deserialize(stringified,bindingContext.ModelType); } } }
然后,动作看起来像:
[HttpPost] public ActionResult Index([FromJson] IEnumerable<GiftModel> gifts)
现在,您可以使用ko.utils.postJson提交数据并使用适当的视图进行响应.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。