开发者

JsonValueProvider not working in ASP.NET MVC3

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="su开发者_运维问答bmit">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>

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"}

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();
}

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?

Thanks in advance.


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;
});

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" });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜