Convert HTML Form to JSON


Option -1:
function form_to_json(selector) {
    var ary = $(selector).serializeArray();
    var obj = {};
    for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
    return obj;
}

//Example
var mydata = form_to_json('#form');
JSON.stringify(mydata);
---------------------------------------------------------

Option-2:
Using Third party JQuery plugin- http://maxatwork.github.io/form2js/

<script src="form2js.js"></script>
<script src="jquery.toObject.js"></script>

var data = $('#form').toObject({skipEmpty:false});
JSON.stringify(data)

Standard JQuery-Ajax Code Template (v.2)

$.ajax({
    type: 'POST',
    url: '../../../../AreaName(If any)/ControllerName/MethodName/',
    //If datatype is of FormCollection, following 3 lines are not needed-
    //====================================================
    //contentType: 'application/json; charset=utf-8',
    //data: "{'agentdata':'"+ agentdata +"'}",
    //OR, data:JSON.stringify({ key1: value1, key2: value2}),
    //dataType: 'json',
    //====================================================
    //If datatype is of FormCollection, following 3 lines are needed-
    //====================================================
    //processData: false,  // tell jQuery not to process the data
    //contentType: false,   // tell jQuery not to set contentType    
    //data: Data,
    //====================================================
    beforeSend: function () {
        $('SubmitButton').attr('disabled', 'disabled');
        $('SubmitButton').html('Working…');
    },
    success: function (result) {
        if (result == 'Success') {
            SuccessfullSaveNotification();
            ResetMainForm(MainForm);
        }
        else {
            ShowRegularError(result);
        }
    },
    error: function (request, status, error) {
        ShowRegularError('Failed to save. Error Details – Request: ' + request + ', Status: ' + status + ', Error: ' + error);
    },
    complete: function () {
        $('SubmitButton').removeAttr('disabled');
        $('SubmitButton').html('Save changes');
    }
});

Sending List/Datatable from MVC Controller to JQuery-AJAX

Option A: Send as List

//Server Side       
public class Person
{
    public int Id { get; set; }
    public String Name { get; set; }
}

[HttpPost]
public JsonResult GetData()
{
    List<Person> persons = PersonManager.GetList();
    return Json(new { ServerResponse = "Success", PersonList = persons },                     
          JsonRequestBehavior.AllowGet);
}
//Client Side
success: function (response) {
      if (response.ServerResponse === "Success") {
          var persons = response.PersonList;                        
          //Looping persons array without any function parameter
          $.each(persons, function () {
                console.log('Id-' + this.Id + ', Name-' + this.Name);
          });

          //Looping persons array with function parameter
          $.each(persons, function (index, person) {
                 console.log('SL-' + index + ', Id-' + person.Id + ', Name-' + person.Name);
                 $.each(person, function (key, value) {
                       console.log(key + ':' + value);
                 });
          });

          //JavaScript Loop
          persons.forEach(function (person,index) {
                console.log('Id-' + person.Id + ', Name-' + person.Name);
            });
      }
},

Option A: Send as DataTable

//Server side
using Newtonsoft.Json;

[HttpPost]
public JsonResult GetData()
{
    DataTable persons = PersonManager.GetList(); //As DataTable
    String SerializedDatatable = JsonConvert.SerializeObject(persons, Formatting.None);
    return Json(new { ServerResponse = "Success", PersonList = persons },                     
                    JsonRequestBehavior.AllowGet);
}


//Client Side
success: function (response) {
         if (response.ServerResponse === "Success") {
               var persons = JSON.parse(response.PersonList);
                       
               //Looping persons array without any function parameter
               $.each(persons, function () {
                      console.log('Id-' + this.Id + ', Name-' + this.Name);
               });

               //Looping persons array with function parameter
               $.each(persons, function (index, person) {
                     console.log('SL-' + index + ', Id-' + person.Id + ', Name-' + person.Name);
                     $.each(person, function (key, value) {
                           console.log(key + ':' + value);
                     });
               });


               //JavaScript Loop
               persons.forEach(function (person,index) {
                   console.log('Id-' + person.Id + ', Name-' + person.Name);
               });
         }
},