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:
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:
============================================================
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.
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:
then use the following Javascript/Jquery code :
Then in the Controller Action method, use the following code:
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.