JsonValueProvider在ASP.NET MVC3中不起作用

问题描述:

我在将ViewModel绑定到MVC3中的json时遇到麻烦.我的非常简单的代码如下...

I'm having trouble binding a ViewModel to json in MVC3. My very simple code is below...

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  <% using (Html.BeginForm("Save", "Home")) {%>    
    <p>
        Cat
    </p>
    <button id="clickMe" type="submit">Click Me</button>
   <% } %>     

  <script type="text/javascript">
    $(function () {
      $('form').submit(function () {
        var cat = {
          Age: 5,
          Weight: 13.5,
          Name: 'Fluffy'
        };

        $.ajax({
          url: '/home/save',
          type: 'post',
          data: JSON.stringify(cat),
          dataType: 'json',
          contentType: 'application/json; charset=utf-8'
        });

        console.info(JSON.stringify(cat));
      });
    });
  </script>
</asp:Content>

在Firebug信息窗口中打印console.info行,因此脚本在正确的时间触发.预期的JSON也显示在Firebug中...

The console.info line is printed in the Firebug info window so the script is firing off at the correct time. The expected JSON also shows up in Firebug...

Source
{"Age":5,"Weight":13.5,"Name":"Fluffy"}

但是,当下面的视图模型进入action方法时,下面的所有属性都未设置...

However, when the viewmodel below comes into the action method below all of its properties are unset...

public class Cat
{
  public int Age { get; set; }
  public double Weight { get; set; }
  public string Name { get; set; }
}

[HttpPost]
public ActionResult Save(Cat form)
{
  return View();
}

我已验证该应用程序启动时JsonValueProviderFactory已在工厂中注册.我确定我在这里缺少了难以置信的简单事物,任何人都可以对此有所了解吗?

I've verified that the JsonValueProviderFactory is registered in the factories when the app starts. I'm sure I'm missing something unbelievably simple here, can anyone shed any light on this?

谢谢.

这应该有效.只是不要忘记通过返回false来取消默认的表单提交:

This should work. Just don't forget to cancel the default form submit by returning false:

$('form').submit(function () {
    var cat = {
        Age: 5,
        Weight: 13.5,
        Name: 'Fluffy'
    };

    $.ajax({
        url: this.href,
        type: this.method,
        data: JSON.stringify(cat),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8'
    });

    return false;
});

还指定了dataType: 'json',因此请确保您的控制器操作返回JSON:

Also you have specified dataType: 'json' so make sure that your controller actions returns JSON:

[HttpPost]
public ActionResult Save(Cat form)
{
    return Json(new { message = "success" });
}