Wednesday, January 22, 2014

Pass Complex JavaScript Object to MVC Controller


In this tutorial I'm going to illustrate how we can pass complex javascript objects to MVC controller.

I have two Model objects called Project and Employee as below.

    public class Project
    {
        public long ProjectID { get; set; }
        public string ProjectName { get; set; }
    }

    public class Employee
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }

And I have view-model called "ProjectViewModel" which contains above models as below.

    public class ProjectViewModel
    {
        public Project Project { get; set; }
        public IList<Employee> EmployeeList { get; set; }
    }
Now I'm going to pass instance of ProjectViewModel and an Employee object to my MVC controller. Here is the controller method.
        [HttpPost]
        public ActionResult Create(ProjectViewModel projectViewModel, Employee anotherEmployee)
        {
            return Content("done");
        }
This is the JavaScript code that we can use to call the controller method.
        var projectViewModel = {};

        var project = {};
        project.ProjectID = 1234;
        project.ProjectName = "Test Project";

        projectViewModel.Project = project;

        var employeeList = [];

        var employee1 = {};
        employee1.Code = "1111";
        employee1.Name = "Saranga";

        var employee2 = {};
        employee2.Code = "2222";
        employee2.Name = "Rathnayaka";

        employeeList.push(employee1);
        employeeList.push(employee2);

        projectViewModel.EmployeeList = employeeList;

        var employee3 = {};
        employee3.Code = "3333";
        employee3.Name = "Test User";

        $.ajax(
  {
      url: 'Project/Create',
      data: JSON.stringify({projectViewModel : projectViewModel, anotherEmployee : employee3}),
      contentType: 'application/json',
      dataType: 'json',
      type: 'POST',
      success: function (data) {
          alert("success");
      },
      error: function () { alert('error'); }
  });

0 comments:

Post a Comment