Search
Close this search box.

Combining jquery form serialize() and JSON.stringify() when doing ajax post in MVC

Most of the times we end up using either $(‘#myform’).serialize() along with default contentType in ajax POST request, OR we use the JSON representation of the form using jquery helper methods, then call JSON.stringify(formData) and then set contentType = “’application/json; charset=utf-8’” inorder to submit form data to the MVC Controller.

The JSON jquery helper is as shown below:

$.fn.serializeObject = function() {
  var o = {};
  var a = this.serializeArray();
  $.each(a, function() {
    if (o[this.name] != = undefined) {
      if (!o[this.name].push) {
        o[this.name] = [o[this.name]];
      }
      o[this.name].push(this.value || '');
    } else {
      o[this.name] = this.value || '';
    }
  });
  return o;
};

Then we use the following to get the form Data in JSON form:

var formData = $(‘#myform’).serializeObject();

hen to convert this JSON object to JSON string we use : data = JSON.stringify(formData);

============================================================

The added advantage of using $(‘#myform’).serialize() along with default contentType in ajax POST request, is that if in the Controller Action method, we have a parameter for “FormCollection formCollection” then this parameter will be populated with the form data as well.

This is particularly helpful when we are using dynamically generated input fields in our HTML form.

============================================================

Similarly the added advantage of using JSON.stringify(formData) is that we can extend the formData (JSON object) with addititional data such as collections, Entities and so on as shown below:

var formData = $('#form').serializeObject();
$.extend(formData, { Contacts : myContacts });
$.extend(formData, { Address : myAddress });
var result = JSON.stringify(formData);

============================================================

Now most of the times, we need both these advantages when submitting formData to Controller action method.

There is no straight forward way to accomplish this.

1 if you need to extend the data and send extension fields(in formcollection) -
    BOTH then we need to do the following to convert the JSON object to
    queryString.2 3 var formData = $('#form').serializeObject();
4 $.extend(formData, { Address : myAddress });
5 5 var result = decodeURIComponent($.param(formData));
6 7 Then use 8 $.ajax(
    9 url: @Url.Action("post url") 10 data: decodeURIComponent(
        $.param(formData)),
    11 dataType: 'json', 12 type: 'POST', 13 success: function() {}, 14) 15

However this works for extending the formData with simple Entities and fields, this does not work when we extend formData with Collections ( e.g. List of Contacts).

However this will work for simple formData extensions like {Address : myAddress}   
If we need to pass (extend formData with ) collections then use the following solution:

1 create hidden field to the HTML Form : 2 < input type = "hidden" id =
    "formHiddenField" name = "formHiddenField" / > 3

then use the following Javascript/Jquery code :

1 var formData = $('#form').serializeObject();
2 $.extend(formData, { Contacts : myContacts });
3 $.extend(formData, { Address : myAddress });
4 var result = JSON.stringify(formData);
5 6 $('#formHiddenField').val(result);
7 8 then submit form using : 9 $.ajax(
    10 url: @Url.Action("post url") 11 data: myForm.serialize(),
    12 dataType: 'json', 13 type: 'POST', 14 success: function() { 15 })

Then in the Controller Action method, use the following code:

1 public virtual ActionResult    PostContacts(string formHiddenField, FormCollection collection, FacebookModel model){
2 
3 var parsed = JsonConvert.DeserializeObject<FacebookModel>(formHiddenField);
4 then use the parsedModel as usual.
5 }

I found this very very useful when extending formData with JSON data collections and also using dynamic HTML fields and capturing them via FormCollection in the controller action methods.Posted on Wednesday,

June 25, 2014 9:11 AM | Back to top

This article is part of the GWB Archives. Original Author: ROHIT GUPTA

Related Posts