2012-07-18 45 views
1

我有問題,從淘汰賽發送json到mvc2控制器的行動。 以下是我在我的視野:淘汰賽和MVC2:發送模型到控制器

var ViewModel = { 
      FirstName: ko.observable("FirstName"), 
      LastName: ko.observable("LastName"), 
      Save: function() { 
       ko.utils.postJson(location.href, this); 
      } 
} 
ko.applyBindings(ViewModel); 

我在控制器的動作:

public virtual ActionResult SomeAction(MyModel model) { 
     //do smth 
     return View(registrationModel); 
} 
public class MyModel { 
    public string FirstName {get;set;} 
    public string LastName {get;set;} 
} 

的問題是,我得到的字符串值引用,如「\」名字\」 「,而且我知道有一些方法可以避免這種情況(在MVC3中使用JSON.stringify)。 我已經試過如下:

ko.utils.postJson(location.href, JSON.stringify({model: this}); 

var json = JSON.stringify({ 
FirstName: this.FirstName(), 
LastName: this.LastName() 
}); 
ko.utils.postJson(location.href, JSON.stringify({model: json}); 

ko.utils.postJson(location.href, json); 

在所有這些3個選項,我得到的模型= null;或者在控制器中的所有值空。

也許有人已經這樣做過?

回答

1

我發現爲了使MVC對象映射工作,您需要將POST的內容類型設置爲「application/json; charset = utf-8」。我從來沒有這樣做使用ko.utils.postJson()之前,但在這裏使用jQuery工作示例:

$.ajax({ 
     url: url, 
     type: "POST", 
     data: ko.toJSON(ViewModel), 
     dataType: "json", 
     contentType: "application/json; charset=utf-8", 
     success: function (response) { 
     }, 
     error: function (response, errorText) { 
     } 
    }); 

注意我使用ko.toJSON序列化模型作爲JSON。