Geeks With Blogs
Rohit Gupta Engaging talk on Microsoft Technologies ....My Resume

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:

1 $.fn.serializeObject = function () { 2 var o = {}; 3 var a = this.serializeArray(); 4 $.each(a, function () { 5 if (o[this.name] !== undefined) { 6 if (!o[this.name].push) { 7 o[this.name] = [o[this.name]]; 8 } 9 o[this.name].push(this.value || ''); 10 } else { 11 o[this.name] = this.value || ''; 12 } 13 }); 14 return o; 15 };

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

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

Then 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:

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

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

 

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 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 2 3 3 var formData = $('#form').serializeObject(); 4 4 $.extend(formData, { Address : myAddress}); 5 5 var result = decodeURIComponent($.param(formData)); 6 6 7 7 Then use 8 8 $.ajax( 9 9 url: @Url.Action("post url") 10 10 data: decodeURIComponent($.param(formData)), 11 11 dataType: 'json', 12 12 type: 'POST', 13 13 success: function(){}, 14 14 ) 15 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


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

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Rohit Gupta | Powered by: GeeksWithBlogs.net