我在将json从knockout发送到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;}
}
问题是我得到了带引号的字符串值,比如"\"FirstName\"",我知道有一些方法可以避免这种情况(在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个选项中,我得到model = null,或者Controller中的所有值都是null。
也许有人以前做过这样的事?
发布于 2012-07-19 01:47:16
我发现为了让MVC对象映射起作用,您需要将帖子的内容类型设置为"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。
https://stackoverflow.com/questions/11546258
复制相似问题