Passing Multiple Models Using Ajax in ASP.NET MVC Step By Step

Introduction

This article explains how to pass multiple models from view to controller using Ajax and how to pass multiple models from view to controller in MVC Step by Step.

Background

In MVC application we use multiple model based on our application. We can pass many models from controller to view and same time as pass many model values pass from view to model. This model article explains how to pass many model values from view to controller using jQuery with the help of Ajax.

Steps for passing multiple models

Step 1

Open Microsoft Visual Studio, open new project and give project name.

Step 2

Select MVC project template and click OK button. Below screen shorts explains how to select MVC template.

Step 3

Add a class files in model folder. Add what are the classes and properties we need for our application. Below screen short explains how to add class file.

Step 4

After adding class, add class Properties. Below coding shows classes and it is properties.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;
 
namespace PassingMultipleModel.Models

{

    public class Customer

    {

        public int CustomerId { set; get; }

        public string CustomerName { set; get; }

        public string Address { set; get; }

    }
 
    public class Employee

    {

        public int EmployeIeId { set; get; }

        public string EmployeeName { set; get; }

        public string Address { set; get; }
    }

 
    public class Common

    {

        public Customer customer { set; get; }

        public Employee employee { set; get; }

    }

 }

Step 5

There are three files are in class files. First class is “Customer” and second class is “Employee”. Multiple classes we cannot pass from controller to view separately so we combine two classes using another class and send to view. Below screen short explains how to combine two classes using another class.

Step 6

Add controller then add action methods in controller. Add view for corresponding action methods and add below code.

@model PassingMultipleModel.Models.Common

@{

    ViewBag.Title = "Index";

}

<h2>Customer</h2>

<table>

    <tr><td>Customer Id</td><td>@Html.TextBoxFor(m=>m.customer.CustomerId)</td></tr>

    <tr><td>Customer Name</td><td>@Html.TextBoxFor(m => m.customer.CustomerName)</td></tr>

    <tr><td>Address</td><td>@Html.TextBoxFor(m => m.customer.Address)</td></tr>

</table>
 
<h2>Employee</h2>

<table>

    <tr><td>Employee Id</td><td>@Html.TextBoxFor(m => m.employee.EmployeIeId)</td></tr>

    <tr><td>Employee Name</td><td>@Html.TextBoxFor(m => m.employee.EmployeeName)</td></tr>

    <tr><td>Address</td><td>@Html.TextBoxFor(m => m.employee.Address)</td></tr>

</table>

<button type="button" id="btnSubmit">Submit</button>

Step 7

Add JsonResult method in controller. We are passing the values from view to this JsonResult method using Ajax.

using PassingMultipleModel.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc; 

 
namespace PassingMultipleModel.Controllers

{

    public class DemoController : Controller

    {

        // GET: Demo

        public ActionResult Index(

        {

            return View();

        }
 
        public JsonResult Process(Common model)

        {

            return Json(JsonRequestBehavior.AllowGet);

        }

    }

}

Step 8

We can get nested class properties id in jQuery using “@Html.IdFor()”. Following way we can read nested class properties value.

var EmpId = $('#@Html.IdFor(m=>m.employee.EmployeeId)').val();

Step 9

Add below jQuery code in button click event for passing multiple models using Ajax from view to controller.

<script>
 
    $("#btnClick").click(function () {      

 
        var customer = {
 
            CustomerId: $('#@Html.IdFor(m=>m.customer.CustomerId)').val(),
 
            CustomerName: $('#@Html.IdFor(m=>m.customer.CustomerName)').val(),
 
            Address: $('#@Html.IdFor(m=>m.customer.Address)').val()

        }
 
        var employee = {
 
            EmployeIeId: $('#@Html.IdFor(m=>m.employee.EmployeeId)').val(),
 
            EmployeeName: $('#@Html.IdFor(m=>m.employee.EmployeeName)').val(),
 
            Address: $('#@Html.IdFor(m=>m.employee.Address)').val()

        } 

 
        var model = {
 
            "customer": customer,
 
            "employee": employee

        } 

 
        alert(model)
 
        $.ajax({
 
            type: "post",
 
            url: "/Demo/Process",
 
            data: model,
 
            datatype: "json",
 
            cache: false,
 
            success: function (data) {
 
                alert("You Multiple Data Passed Successfully");
 
            },
 
            error: function (xhr) {
 
                alert('No Valid Data');
 
            }

        });

 
    });
 
</script>

 

Explanation

We create JSON object like below. Class object name and JSON variable name should be equal and same as class properties and JSON properties should be equal.

Customer class we have created like below and same as created object for Customer class in another one class like Common.

   

     public class Customer
     {
        public int CustomerId { set; get; }

       public string CustomerName { set; get; }

       public string Address { set; get; }

   }
 
          public class Employee

   {

       public int EmployeeId { set; get; }

       public string EmployeeName { set; get; }

       public string Address { set; get; }

   }

 
   public class Common

   {

       public Customer customer { set; get; }

       public Employee employee { set; get; }

   }

In jQuery we can fetch and store data in variable as Json format what are the values stored in class properties. 
   

    var customer = {
 
            CustomerId: $('#@Html.IdFor(m=>m.customer.CustomerId)').val(),
 
            CustomerName: $('#@Html.IdFor(m=>m.customer.CustomerName)').val(),
 
            Address: $('#@Html.IdFor(m=>m.customer.Address)').val()
 
        }

  
 
var employee = {
 
            EmployeIeId: $('#@Html.IdFor(m=>m.employee.EmployeeId)').val(),
 
            EmployeeName: $('#@Html.IdFor(m=>m.employee.EmployeeName)').val(),
 
            Address: $('#@Html.IdFor(m=>m.employee.Address)').val()

        } 

 
                We can store multiple set of Json data store in single variable as like below code in JQuery. 

 
        var model = {
 
            "customer": customer,
 
            "employee": employee

        }

Below screen shots shows how create properties normal class and in same as jQuery.

Step 10

Now build and run the solution. After run we can see the main page then enter the value and click Submit button.

Step 11

Now put break point and can see values in controller, what are the values entered in view page.

After processed data finally show the success message if everything processed successfully.

Conclusion

Hope this article helps many developers and students know how to pass multiple model passing from view to controller using Ajax in step by step way. If you have any query please ask.