AJAX Post Using Serialize Data

AJAX posts are great for calling controller methods.  However, if you have a lot of parameters or if your method only takes a model there is a nice and simple answer to sending all of the data in a quick and efficient matter.  The AJAX call allows you to .serialize() the form that the data is coming from.  It can select on individual elements like <input> or <textarea> but it is typically easier to select the surrounding form. Let’s look at how this call is constructed.

$.ajax({
    type: 'POST',
    url: '/Controller/EmailAction',
    data: $('#form-content').serialize(),
    dataType: "json",
    success: function (data) {
        //show a success message
    },
    error: function () {
        //log failure/show message
    }
});

As you can see it is pretty straight forward.  Data gets set to the form, which in this case is $(‘#form-content’).  From there you call a .serialize() on the form as show above. So if we look at the controller method this is all you need for your method declaration.

public JsonResult EmailAction(MyModel model)
{
       try
       {
              //Processing here.
       }
       catch (Exception ex)
       {
              //log
       }

       return Json(result);
}

It is obviously not a complete method by any means but as you can see it only takes a model.  The magic that happens is when you name the input elements the same as in the model, when you serialize and make the request they are automatically mapped over because it generates a query string of the input elements and they are mapped over to the model.  This makes something like a registration form that has numerous fields it becomes very simple to create a model and just call .serialize() and it’s all done for you.  I found this way a lot easier and more organized then creating methods with tons of parameters and helps to minimize error if you change the names of fields as there are less places to make changes.


StackOverflow Profile