2
votes

The reply at

MVC3 Pass Model view to controller using javascript

implies that this was impossible, at least for MVC 3.

I was wondering if there is any way in MVC 4 to quickly pass the entire form contents (represented by the model) from the .cshtml (razor) view to the controller in JavaScript.

For example, if I select a dropdown, I may want to return all fields from a form to the controller which will take appropriate action.

Obviously, for large forms it is undesirable to have to do this element-by-element

2
Why is it impossible (on MVC 3)? I do it all the time. Have you ever heard about JSON, AJAX, Serialization, JsonNET, etc? Actually, you don't pass anything. You submit information to an Action in the Controller.melancia
Do you have a small example of the JSON syntax to pass the entire model back to the controller from JavaScript? Thanks very much. I'm from the US, but watch a lot of UK TV, listen to UK music, etc.JosephDoggie
I live in the UK, but I'm Italian/Brazilian. :)melancia

2 Answers

5
votes

Basically, you can do it calling an AJAX POST:

JS (using jQuery):

$('form').on('submit', function (event) {
    // Stop the default submission
    event.preventDefault();

    // Serialize (JSON) the form's contents and post it to your action
    $.post('YourAction', $(this).serialize(), function (data) {
        // If you want to do something after the post
    });
});

Controller Action:

public ActionResult YourAction(string JSONmodel)
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

    MyModel model = serializer.Deserialize(JSONmodel, typeof(MyModel));

    // Now you can do whatever you want with your model
}

UPDATE

For more complex objects, you can use a third part solution for serialization/deserialization. It's well documented and broaden used:

Json.NET: http://json.codeplex.com/

1
votes

Yes it is possible in a simpler way.

  1. Alternate of example provided by MelanciUK.

    $('form').on('submit', function (event) {
        // Stop the default submission
           event.preventDefault();
    
       // User same property name as in Model
          $.post('YourAction', {prop1 : 'a', prop2 : 'b'}, function (data) {
       // If you want to do something after the post
    });
    

    });

    [HttpPost]
     public ActionResult SampleAction(SampleModel sModel)
      {
    
      }
    

You can achieve the same thing by stadard MVC(ModelBinding) convention i.e. no need to serialize and deserialize.