views:

116

answers:

2

I'm trying to use the new JSON ModelBinders in MVC 3 which Scott Guthrie talks about in his blog.

My example is very similar to the one he is using. I have a model with 3 values which I am trying to POST to the server.

The model looks like this:

public class CommentViewModel
{
    public string Product { get; set; }
    public string Text { get; set; }
    public string Author { get; set; }
}

The JavaScript looks like this:

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

The controller action looks like this:

[HttpPost]
public ActionResult Add(CommentViewModel comment)
{
      // ...
}

The alert I'm getting (the one inside the JavaScript post) gives me something likes this:

value={"Product":"Classic","Text":"the comment","Author":"me"}

I am expecting the properties in the model to be populated on the server, but all the properties are null. I'm using ASP.NET MVC 3 Preview 1.

+1  A: 

pretty sure you need to change the following lines

$.ajax({                                                    
    url: "/Home/Add",
    type: "POST",
    data: comment,
    datatype: "json",
    success: function (data) {
        alert(data);
    }
});

Notice i've removed the stringify and the contenttype

BuildStarted
+3  A: 

I think it might be because ASP.NET MVC 3 Preview 1 is not registering the JsonValueProviderFactory automagically as expected.

Put the following snippet in Global.asax to manually register it, it should fix solve your problem:

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())
kobusb