2011-05-17 98 views
5

我有一个用Knockout.js创建的表单。当用户按下提交按钮时,我将视图模型转换回模型并试图提交给服务器。我试过了:提交json到MVC3操作

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"); } 
}); 

这将获取数据到服务器与正确的数据在其中。

但我想要的是提交数据,以便我的控制器可以重定向到正确的视图。有什么建议吗?

回答

11

史蒂夫·桑德森有演示得到提交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来提交您的数据和以适当的观点回应。

+0

这一工作十分感谢。我正在关注你提到的例子。我错过了属性部分。 – 2011-05-17 20:37:20

-2

此外,它提到的例子,但你可能需要改变你的JavaScript调用是这样的:

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

这实际上是不正确的。 – youwhut 2011-09-23 13:39:19

+1

这在另一个答案中的帖子中已有介绍。 – 2012-05-11 16:41:01