将json提交给MVC3操作

我有一个用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-样式/

它的要点是他创建了一个名为“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 gifts) 

现在,您可以使用ko.utils.postJson提交数据并使用适当的视图进行响应。

此外,它在上面提到的示例中,但您可能需要将JavaScript调用更改为:

 ko.utils.postJson(location.href, { viewModel: this.viewModel });