ASP.NET MVC 3 JSON ModelBinders not working

I am 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 it uses. I have a model with 3 values ​​that I am trying to execute POST on the server.

The model is as follows:

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

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 action of the controller is as follows:

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

The warning I get (the one inside the JavaScript message) gives me something like this:

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

I expect that the properties in the model will be populated on the server, but all the properties are zero. I am using ASP.NET MVC 3 Preview 1.

+3
source share
2 answers

, , ASP.NET MVC 3 Preview 1 JsonValueProviderFactory , .

Global.asax, , :

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())
+4

,

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

, stringify contenttype

+2

Source: https://habr.com/ru/post/1762495/


All Articles