我正在尝试在MVC3中使用Scott Guthrie在his blog中提到的新的JSON ModelBinders。
我的示例与他使用的示例非常相似。我有一个有3个值的模型,我正试图将其发布到服务器上。
该模型如下所示:
public class CommentViewModel
{
public string Product { get; set; }
public string Text { get; set; }
public string Author { get; set; }
}JavaScript如下所示:
$("#addComment").click(function () {
var comment = {
Product: $("#productName").html(),
Text: $("#comment").val(),
Author: $("#author").val()
};
alert("value=" + JSON.stringify(comment));
$.ajax({
url: "/Home/Add",
type: "POST",
data: JSON.stringify(comment),
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
}); 控制器操作如下所示:
[HttpPost]
public ActionResult Add(CommentViewModel comment)
{
// ...
}我收到的警报( JavaScript帖子中的那个)给了我一些类似的东西:
value={"Product":"Classic","Text":"the comment","Author":"me"}我希望在服务器上填充模型中的属性,但所有属性都为空。我使用的是ASP.NET MVC3预览版1。
发布于 2010-09-01 14:20:11
我认为这可能是因为ASP.NET MVC3Preview1没有像预期的那样自动注册JsonValueProviderFactory。
将以下代码片段放在Global.asax中手动注册,它应该可以修复并解决您的问题:
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())发布于 2010-09-01 05:38:53
我非常确定您需要更改以下代码行
$.ajax({
url: "/Home/Add",
type: "POST",
data: comment,
datatype: "json",
success: function (data) {
alert(data);
}
});注意,我删除了stringify和contenttype
https://stackoverflow.com/questions/3611347
复制相似问题