Friday, April 5, 2013

ASP.NET MVC Call multiple collection parameter action method from AJAX

Call multiple collection parameter action method using AJAX
This example is used to demonstrate how to send multiple collection data to a action method in MVC. 
First i have defined the View Model which is the type of the collection that is used as the parameter of the action method.
Second the Controller Action Method is defined to show that it takes to List<Employee> collections.
Third listing explains the View - javascript which stringify the object and send a AJAX request to the server.
View Model
public class Employee
{
  public int ID{get;set;}
  public string Name{get;set;}
  public string Age{get;set;}
}  
 
Controller Action Method

public ActionResult SaveData(List<Employee> updateEmployee, List<Employee> deleteEmployee)
{

 try
 {
   //Do your processing
 } 
 catch(exception)
 {
   // do your loggin
 }


View - javascript 
$(document).ready(function(){
 // Here i would like to simulate the collections by adding them statically for simplicity
 var uEmployee = new Object();
 var dEmployee = new Object();
//Create update employees
 var ut1Emp = new Object();
 ut1Emp.ID = 1; ut1Emp.Name="Desmond"; ut1Emp.Age="27";
 var ut2Emp = new Object();
 ut2Emp.ID = 2; ut2Emp.Name="Maria"; ut2Emp.Age="1";
 uEmployee.Push(ut1Emp );
 uEmployee.Push(ut2Emp );
 //Create delete employees
 var dt1Emp = new Object();
 dt1Emp.ID = 3; dt1Emp.Name="Jacintha"; dt1Emp.Age="25";
 var dt2Emp = new Object();
 dt2Emp.ID = 4; dt2Emp.Name="Angel"; dt2Emp.Age="1";
 dEmployee.Push(dt1Emp );
 dEmployee.Push(dt2Emp );

 var param = { 'updateEmployee': uEmployee, 'deleteEmployee': dEmployee}; 

 $.ajax({ url: "SaveData",
          type: 'POST',
          contentType: "application/json; charset=utf-8" , // this is important
          data: JSON.stringify(param), // This is important
          failure: function (errorMSG){
              alert('Error occurred on saving data');

          },
          success: function (data) {
              alert('Successfully saved');

          }
        });

});