2011-05-17 96 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