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:
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "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:
-
-
-
- public class OrderModel
- {
- public string ProductCode { get; set; }
- public string ProductName { get; set; }
- public Int16 Qty { get; set; }
- public double Price { get; set; }
- public double TotalAmount { get; set; }
- }
- public class OrderDetail
- {
-
-
-
- public List<OrderModel> OrderDetails { get; set; }
-
- }
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
- public class OrderController : Controller
- {
-
-
-
-
- public ActionResult PlaceOrder()
- {
- List<OrderModel> objOrder = new List<OrderModel>()
- {
- new OrderModel {ProductCode="AOO1",ProductName="Windows Mobile",Qty=1,Price=45550.00,TotalAmount=45550.00 },
- new OrderModel {ProductCode="A002",ProductName="Laptop",Qty=1,Price=67000.00,TotalAmount=67000.00 },
- new OrderModel {ProductCode="A003",ProductName="LCD Television",Qty=2,Price=15000.00,TotalAmount=30000.00 },
- new OrderModel {ProductCode="A004",ProductName="CD Player",Qty=4,Price=10000.00,TotalAmount=40000.00 }
- };
-
- OrderDetail ObjOrderDetails = new OrderDetail();
- ObjOrderDetails.OrderDetails = objOrder;
- return View(ObjOrderDetails);
- }
-
-
-
-
-
- [HttpPost]
- public ActionResult PlaceOrder(OrderDetail Order)
- {
-
-
- return View();
- }
- }
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
- @model GetHTMLTableRecordsInMVC.Models.OrderDetail
- @{
- ViewBag.Title = "www.cpmpilemode.com";
- }
- <hr />
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10 text-right">
- <input type="button" value="Add Product" class="btn btn-primary" />
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-12">
- <table class="table table-condensed table-hover">
- <tr>
- <th>
- Product Code
- </th>
- <th>
- Product Name
- </th>
- <th>
- Quantity
- </th>
- <th>
- Price
- </th>
- <th>
- Total Amount
- </th>
- </tr>
- @{
- //To make unique Id
- int i = 0;
- foreach (var item in Model.OrderDetails.ToList())
- {
-
- <tr>
- <td>
-
-
- @Html.EditorFor(o => o.OrderDetails[i].ProductCode, new { @id = "ItemCode_" + i })
- </td>
- <td>
- @Html.EditorFor(o => o.OrderDetails[i].ProductName, new { @id = "ProductName_" + i })
- </td>
- <td>
- @Html.EditorFor(o => o.OrderDetails[i].Qty, new { @id = "Qty_" + i })
- </td>
- <td>
- @Html.EditorFor(o => o.OrderDetails[i].Price, new { @id = "Price_" + i })
- </td>
- <td>
- @Html.EditorFor(o => o.OrderDetails[i].TotalAmount, new { @id = "Price_" + i })
- </td>
-
- </tr>
- i++;
- }
- }
- </table>
- </div>
- </div>
- <hr />
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10 text-center">
- <input type="submit" value="Place Order" class="btn btn-primary" />
- </div>
- </div>
- </div>
- }
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: