Search code examples
asp.net-mvcjsonrazorstringifyjsonserializer

MVC3 (Razor) Json Get deserialized data in the Controller


I need help again with Asp.Net MVC (Razor View Engine). In my View (Index) I have

@model IEnumerable<Movie>

I want to pass the Model to the Controller: I stringify the model in this way:

<script type="text/javascript">
function postData(){
var urlact='@Url.Action("createDoc")';
var model ='@Html.Raw(Json.Encode(Model));

$.ajax({
    data: JSON.stringify(model),
    type:"POST",
    url:urlact, 
    datatype:"json",
    contentType:"application/json; charset=utf-8"
});
}
</script>

Everything seems to work, cause I know the stringified data is:

'[{"ID":1,"Title":"The Lord of the Rings: The Fellowship of the Ring","ReleaseDate":"\/Date(1007938800000)\/","Genre":"Fantasy","Price":93000000.00},{"ID":2,"Title":"The Lord of the Rings: The Two Towers","ReleaseDate":"\/Date(1039042800000)\/","Genre":"Fantasy","Price":94000000.00},{"ID":3,"Title":"The Lord of the Rings: The Return of the King","ReleaseDate":"\/Date(1070233200000)\/","Genre":"Fantasy","Price":94000000.00}]';

The problem is: in Controller, methodName "createDoc" (as declared in the script) I cannot access to the stringified data. Following some samples founded on the web, my method is something like this:

[HttpPost]
    public ActionResult createDoc(IEnumerable<Movie> movies)
    {
        //...using movies list
        return View();
    }

Why can't I access to the stringified data? How can I do it, is there some method to call to deserialize the model in the Controller method? Also, can I use the serialize() method instead of the stringify() one? If so, what's the syntax, View & Controller side?

Thank you.


Solution

  • You've already got stringified data in your JavaScript variable model. You only need to call JSON.stringify on objects which aren't strings.

    If you want to post the data to your action without modifying model, just pass in model without the JSON.stringify and the ModelBinder will take care of deserializing it to IEnumerable<Movie> for you.

    If you want to use model as something other than a string, you'll want to call JSON.parse on the string. In other words:

    var model = JSON.parse('@Html.Raw(Json.Encode(Model))');
    

    Then, you'd want to keep your JSON.stringify call.

    Finally, stringify is a method on a browser-specific object JSON, whereas serialize is a method on the ASP.NET MVC-specific Json object. Two different worlds, same name.