1

I'm trying to figure out a way to pass the entire class from my View to a Controller with Javascript/AJAX.

I know the following Ajax code can be used to pass just the ID but can I pass the entire model ?

    @model  User
    $.ajax(
        {
            type: "POST",
            url: "\User\",
            data: @model.id,
            success:
                reloadPage()
        });

I saw the following solution while searching: Is there a way to pass a "C#" object to a controller via AJAX?

Can I simply do this instead ? :

    @model  User
    $.ajax(
        {
            type: "POST",
            url: "\User\",
            data: @model,
            success:
                reloadPage()
        });

Will this work ? How safe ? What's the best way ?

Community
  • 1
  • 1
InspiredBy
  • 4,271
  • 6
  • 40
  • 67

4 Answers4

4

Check out the JavascriptSerializer.Serialize() method. So something like this:

@model  User
$.ajax({
    type: "POST",
    url: "\User\",
    data: JSON.parse(@(new JavascriptSerializer().Serialize(Model))),
    success: reloadPage
});

Essentially, this serializes your model to a JSON string, which is then parsed client side back into a JS object, which is then passed into the AJAX request. When the request hits the server, MVC model binding handles constructing an instance of the model based off the JSON object.

Note that JSON.parse is not supported in older versions of IE. You can get json2.js to shim the method for IE.

Scott Hamper
  • 371
  • 2
  • 2
  • 3
    Thanks. Here is the namespace for those looking at this later: System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model) – InspiredBy Apr 06 '12 at 22:10
  • 2
    But doesn't this only serialize what's there when the page loads and not a created/updated model in the view? – klkitchens Feb 09 '13 at 15:53
  • 1
    Case typo, the class is called JavaScriptSerializer, with capital S on Script. (not JavascriptSerializer) – Martin Dec 19 '14 at 00:02
2

Although not best practice, if there is no other way to get this data then you may pass the data via tempdata

View:

@{
 TempData["myModel"] = Model;
}

Controller:

var myModel = TempData["myModel"];
TempData.Remove("myModel");
Travis J
  • 81,153
  • 41
  • 202
  • 273
2

Create a Json object with the same properties as original object, Give the Json object name as controller parameter name. Pass the Json object to Controller Using AJAX request

MVC model binding will takecare of remaining things

Raghuveer
  • 2,630
  • 3
  • 29
  • 59
  • So when the User object is passed to a view model initially it needs to be a JSON type? What about on the receiving end, once I send it further from the view to the next controller with this logic? Will the framework automatically parse it from JSON back to User type ? – InspiredBy Apr 06 '12 at 01:53
  • Once Check this Question's Answer [link](http://stackoverflow.com/questions/560575/asp-net-mvc-how-to-pass-json-object-from-view-to-controller-as-parameter) – Raghuveer Apr 06 '12 at 01:57
  • Ok so it seems that before MVC3 JSON to class model binding had to be handled manually. Now with MVC3 it's handled automatically. Quick question before I close it. Is it possible to convert my Model to JSON when I'm already working with the view? Or just the model have to be of JSON type be the time it becomes a View model ? – InspiredBy Apr 06 '12 at 20:38
1

try using the serialize (jQuery)

eg.

$.ajax({
   type: "POST",
   url: "\User\",
   data: $(form).serialize(),
   success: reloadPage()
});