Pass Dynamically Added HTML Table Records List To Controller In ASP.NET MVC

In this article we will learn how to pass dynamically added HTML Table records list to Controller in ASP.NET MVC.

Background

Many times we need to post a list of records to controller instead of a single record to controller such as dynamically added html table records etc . Also I have learned on many forum posts regarding the problem in posting a list of records to controller, as many are saying while posting list of records we are getting only one record at controller instead of list of records . So by considering this requirement I have decided to write this article . Now let's learn step by step which helps beginners to learn how to get list of records into ASP.NET MVC controller .
 
Scenario

Let's consider we have a requirement in which a single user can add multiple orders of products at a time instead of  ordering one by one. So in this scenario we need to create one single view from a complex model that is from multiple models where one model can be used to hold customer information and the second model used to hold the list of records .

So let's demonstrate the preceding scenario by creating one simple ASP.NET MVC application

Step 1: Create an MVC Application.

Now let us start with a step by step approach from the creation of a simple MVC application as in the following:

  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".

  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
 

Step 2: Create Model Class

Now let us create the model class file named OrderModel.cs by right clicking on model folder as in the following screenshot:

 

Note:

It is not mandatory that Model class should be in Models folder, it is just for better readability; you can create this class anywhere in the solution explorer. This can be done by creating different folder names or without folder name or in a separate class library.

OrderModel.cs class file code snippet:
  1. /// <summary>  
  2.    /// To hold order details  
  3.    /// </summary>  
  4.   public class OrderModel  
  5.    {  
  6.        public string ProductCode { getset; }  
  7.        public string ProductName { getset; }  
  8.        public Int16 Qty { getset; }  
  9.        public double Price { getset; }  
  10.        public double TotalAmount { getset; }  
  11.    }  
  12.   public class OrderDetail  
  13.    {  
  14.        /// <summary>  
  15.        /// To hold list of orders  
  16.        /// </summary>  
  17.        public List<OrderModel> OrderDetails { getset; }  
  18.   
  19.    } 
 Step 3: Add Controller Class.

Now let us add the MVC 5 controller as in the following screenshot:
 
 

After clicking on Add button it will show the window. Specify the Controller name as Order with suffix Controller.

Note:

The controller name must be having suffix as 'Controller' after specifying the name of controller. Now modify the default code in OrderController.cs class file to bind HTML table in view from strongly typed model class with list of records and getting those list of records into controller, after modifying code will look like as follows,

OrderController.cs
  1.   public class OrderController : Controller  
  2.     {  
  3.         /// <summary>  
  4.         /// Get list of records with View     
  5.         /// </summary>  
  6.         /// <returns></returns>  
  7.         public ActionResult PlaceOrder()  
  8.         {  
  9.             List<OrderModel> objOrder = new List<OrderModel>()  
  10.             {  
  11.  new OrderModel {ProductCode="AOO1",ProductName="Windows Mobile",Qty=1,Price=45550.00,TotalAmount=45550.00 },  
  12. new OrderModel {ProductCode="A002",ProductName="Laptop",Qty=1,Price=67000.00,TotalAmount=67000.00 },  
  13. new OrderModel {ProductCode="A003",ProductName="LCD Television",Qty=2,Price=15000.00,TotalAmount=30000.00 },  
  14. new OrderModel {ProductCode="A004",ProductName="CD Player",Qty=4,Price=10000.00,TotalAmount=40000.00 }  
  15.             };  
  16.   
  17.             OrderDetail ObjOrderDetails = new OrderDetail();  
  18.             ObjOrderDetails.OrderDetails = objOrder;  
  19.             return View(ObjOrderDetails);  
  20.         }  
  21.         /// <summary>  
  22.         /// Get list of records from view  
  23.         /// </summary>  
  24.         /// <param name="Order"></param>  
  25.         /// <returns></returns>  
  26.         [HttpPost]  
  27.         public ActionResult PlaceOrder(OrderDetail Order)  
  28.         {  
  29.   
  30.   
  31.             return View();  
  32.         }  
  33.     } 
Step 4:

Creating strongly typed view named PlaceOrder using OrderDetail class. Right click on View folder of created application and choose add view, select OrderDetail model class and scaffolding template List   as,
 
 

Click on Add button then it will create the view named PlaceOrder , Now open the PlaceOrder.cshtml view, Then some default code you will see which is generated by MVC scaffolding template, Now modify default code to make as per our requirements, After modifying the code it will look like the following,

PlaceOrder.cshtml
 
  1. @model GetHTMLTableRecordsInMVC.Models.OrderDetail  
  2. @{  
  3.     ViewBag.Title = "www.cpmpilemode.com";  
  4. }  
  5. <hr />  
  6. @using (Html.BeginForm())  
  7. {  
  8.     @Html.AntiForgeryToken()  
  9.   
  10.     <div class="form-horizontal">  
  11.         <div class="form-group">  
  12.             <div class="col-md-offset-2 col-md-10 text-right">  
  13.                  <input type="button" value="Add Product" class="btn btn-primary" />  
  14.             </div>  
  15.         </div>  
  16.         <div class="form-group">  
  17.             <div class="col-md-12">  
  18.                 <table class="table table-condensed table-hover">  
  19.                     <tr>  
  20.                         <th>  
  21.                             Product Code  
  22.                         </th>  
  23.                         <th>  
  24.                             Product Name  
  25.                         </th>  
  26.                         <th>  
  27.                             Quantity  
  28.                         </th>  
  29.                         <th>  
  30.                             Price  
  31.                         </th>  
  32.                         <th>  
  33.                             Total Amount  
  34.                         </th>  
  35.                     </tr>  
  36.                     @{  
  37.                         //To make unique Id  
  38.                         int i = 0;  
  39.                         foreach (var item in Model.OrderDetails.ToList())  
  40.                         {  
  41.   
  42.                             <tr>  
  43.                                 <td>  
  44.   
  45.   
  46.                                     @Html.EditorFor(o => o.OrderDetails[i].ProductCode, new { @id = "ItemCode_" + i })  
  47.                                 </td>  
  48.                                 <td>  
  49.                                     @Html.EditorFor(o => o.OrderDetails[i].ProductName, new { @id = "ProductName_" + i })  
  50.                                 </td>  
  51.                                 <td>  
  52.                                     @Html.EditorFor(o => o.OrderDetails[i].Qty, new { @id = "Qty_" + i })  
  53.                                 </td>  
  54.                                 <td>  
  55.                                     @Html.EditorFor(o => o.OrderDetails[i].Price, new { @id = "Price_" + i })  
  56.                                 </td>  
  57.                                 <td>  
  58.                                     @Html.EditorFor(o => o.OrderDetails[i].TotalAmount, new { @id = "Price_" + i })  
  59.                                 </td>  
  60.   
  61.                             </tr>  
  62.                             i++;  
  63.                         }  
  64.                     }  
  65.                 </table>  
  66.             </div>  
  67.         </div>  
  68.         <hr />  
  69.         <div class="form-group">  
  70.             <div class="col-md-offset-2 col-md-10 text-center">  
  71.                 <input type="submit" value="Place Order" class="btn btn-primary" />  
  72.             </div>  
  73.         </div>  
  74.     </div>  
  75.  } 
Common issues

While binding list of records your control Id's must be unique , otherwise same first record will repeat in all lists. So to avoid this we need to maintain  unique id's for control . As we have maintained in preceding view manually by using incremental i counter and model properties .
 
Now after adding the Model, View and controller into our project. The solution explorer will look like as follows,
 
 

Now we have done all coding to upload files .

Step 5 :
Now run the application. After running the application initial screen will look like as follows,
 


In preceding table we are adding orders (records) dynamically. Put break point on PlaceOrder action result method and click on Place Order button. Now the reference variable Order of OrderDetail class will show the four records in debug mode as,
 
 
In the preceding image you can see that four records list count which is coming from view because we have added four records into the table . Now Expand the OrderDetails node it will show the following records,
 
 
I hope from all preceding examples we have learned how to pass dynamically added HTML table records list to controller in ASP.NET MVC.

Note:
  • Download the Zip file of the sample application for a better understanding.
  • Add product button is just for scenario purpose , In next article I will explain how to add dynamic records into html table .
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary

I hope this article is useful for all readers. If you have any suggestions please contact me.

Read more articles on ASP.NET: