DotNetCurry Logo

ASP.NET MVC: Using Multiple Model Objects as Input Parameters to Controller Action Method

Posted by: Mahesh Sabnis , on 2/19/2016, in Category ASP.NET MVC
Views: 25027
Abstract: Pass multiple objects to the Controller actions which accepts multiple model objects as input parameters.

In ASP.NET MVC, the controller and its actions methods play a very important role in the application. It’s the Controller which accepts the posted data from the View and passes it to the Model and vice-versa. Generally, when we write an MVC Controller, we pass a single model object as an input parameter. However sometimes we may need to pass multiple model objects as an input parameters to the Action method. In this case, we need to make some changes in the Client-Side code. One fact while scaffolding a view in MVC is that since we can pass only one model object to generate View and its HTML helpers with Model binding, we cannot use more than one model object at a given time in a View.

 

In this article, we will discuss how to post multiple model object values from View to the Controller action method.

This application is implemented using Visual Studio 2015. Feel free to use VS 2013.

Step 1: Open Visual studio and create a new ASP.NET Web application of the name Multi_model_action as shown in the following image

aspnet-mvc-web-app

Click on Ok button, select Empty MVC application from the window as shown in the following image:

mvc-app

This will create an MVC application.

Step 2: In this project, add a new Sql Server Database in the App_Data folder of name ApplicationDB.mdf.

Step 3: We will use ADO.NET Entity Framework with the Code-First approach to generate tables. In the Models folder, add a new ADO.NET Entity Data Model of the name ApplicationEntities. This will start the wizard, select the Code-First from Database as shown in the following image

ef-code-first

Select ApplicationDB.mdf in the wizard. Once the wizard completes, the Model folder will be added with ApplicationEntities.cs class file.

Step 4: In the Models folder, add a new class file of name ModelClassses.cs. In this class file add the following classes:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Multi_model_action.Models
{
    public class Order
    {
        [Key]
        public int OrderId { get; set; }
        public string CustomerName { get; set; }
        public ICollection<OrderItemDetails> OrderDetails { get; set; }
    }

    public class OrderItemDetails
    {
        [Key]
        public int ItemId { get; set; }
        public string ItemName { get; set; }
        public int Quantity { get; set; }
        public int OrderId { get; set; }
        public Order Order { get; set; }
    }
}

The above classes contains Order and OrderItemDetails class. The Order class contains collection of OrderItemDetails.

 

Step 5: In the ApplicationEntities class, add the following properties:

public DbSet<Order> Orders { get; set; }
public DbSet<OrderItemDetails> OrderItemDetails { get; set; }

The above properties will be used to map the model classes added in Step 4 with Database tables.

Step 6: In the Controllers folder, add a new folder of name OrderManagerController. Add the following action methods in this controller

using System.Web.Mvc;
using Multi_model_action.Models;

namespace Multi_model_action.Controllers
{
    public class OrderManagerController : Controller
    {
        ApplicationEntities ctx;

        public OrderManagerController()
        {
            ctx = new ApplicationEntities(); 
        }

        // GET: OrderManager
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()    
        {
            return View();
        }

        public JsonResult SaveOrder(Order order, OrderItemDetails [] orditemdetails)
        {
            ctx.Orders.Add(order);
            foreach (var item in orditemdetails)
            {
                item.OrderId = order.OrderId;
                ctx.OrderItemDetails.Add(item);
            }
            ctx.SaveChanges();
            return Json(true,JsonRequestBehavior.AllowGet);
        }
    }
}

The above controller defines an instance of the ApplicationEntities for performing Database operations. The SaveOrder() method accepts Order and array of OrderItemDetails objects as input parameters. This method contains logic for inserting Order and OrderItemDetails in their respective tables.

Step 7: In this project, add jQuery references using NuGet Package Manager.

Step 8: Scaffold an empty view from the Create action method. In this view, add the following script and Markup:

@{
    ViewBag.Title = "Create";
}

<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
http://~/scripts/jquery-2.2.0.min.js
http://~/scripts/bootstrap.min.js

    $(document).ready(function () {
        $("#btnSave").on('click', function () {
            var url = '@Url.Action("SaveOrder", "OrderManager")';
            var data = [];

            data.push(
                 {
                     ItemName: 'Laptop',
                     Quantity: 1000,
                 },
                 {
                     ItemName: 'Desktop',
                     Quantity: 900,
                 }
                );
            $.ajax({
                url:url,
                type:"POST",
                data:{
                    order:{
                      CustomerName:'MS'
                    },
                    orditemdetails:data
                },
                datatype:'json',
                ContentType:'application/json;utf-8'
            }).done(function(resp){
                alert('Success ' +resp);
            }).error(function(err){
                alert("Error " + err.status);
            });

        });

    });


<body>
    <input type="button" value="Save" id="btnSave" class="btn btn-success"/>
</body>

The above script defines JavaScript array of name data. This contains two records. The script contains $.ajax() call which is used to post data to the Controller action method. The data is posted using following syntax:

data:{
    order:{
      CustomerName:'MS'
    },
    orditemdetails:data
},

The data accepts JSON object with keys as order and orderitemdetails. The post request will be made to the SaveOrder action method.

Apply a breakpoint on SaveOrder action method. Run the application, the View will display the Save button. Click on this button, the breakpoint will hit and input parameters passed to this action method will display posted data as shown in following image:

order-break

orderdetails-break

Above images show the posted data. Use F10 to complete the debugging, this will save data in tables by creating tables in the database.

Conclusion:

Using jQuery (or other client-side libraries) are one of the best options using which we can pass multiple objects to the Controller actions which accepts multiple model objects as input parameters.

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!