ScottGuthrieがブログで説明しているMVC3の新しいJSONModelBindersを使用しようとしています。
私の例は彼が使用しているものと非常に似ています。サーバーにPOSTしようとしている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"}
モデルのプロパティがサーバーに入力されることを期待していますが、すべてのプロパティがnullです。ASP.NETMVC3プレビュー1を使用しています。