简体   繁体   中英

MVC4 passing all form data (model) from javascript to controller — is it possible?

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

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/

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 ie no need to serialize and deserialize.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM