You can use the BeginCollectionItem html helper partial view for your model to create collection items with unique indexers and allow collection bindings in the return mail. Please note that you do not specify the type of the NorthOrderDetails property, but form your previous questions, I accept it NorthOrderDetails.cs
Create a partial for NorthOrderDetails.cs
Views/YourController/_NorthOrderDetails.cshtml
@model NorthOrderDetailscs @using(Html.BeginCollectionItem()) { <tr> @Html.HiddenFor(m => m.ProductName) <td>@Html.DisplayFor(m => m.ProductID)</td> <td>@Html.DisplayFor(m => m.ProductName)</td> <td>@Html.TextBoxFor(m => m.Quantity)</td> <td>@Html.TextBoxFor(m => m.UnitPrice)</td> <td> <button type="button" class="delete" data-id="@Model.ProductID">Delete</button> @Html.HiddenFor(m => m.ProductID) @Html.HiddenFor(m => m.ProductName) </td> </tr> }
Side notes:
- Do not enable hidden input for
Index - An
<input> not a valid child of the <tr> element (put hidden inputs inside the <td> element String.Format("{0}", Model.NorthOrderDetails[i].UnitPrice does absolutely nothing (if you want to format it as (say) a currency, it will be @Html.TextBoxFor(m => m.UnitPrice. "{0:C}") )
Now you can remove the for loop in the main view and replace it with
<table id="Products" class="Products"> <thead> <tr> <th>ProductId</th> <th>Productname</th> <th>Quantity</th> <th>UnitPrice</th> </tr> </thead> <tbody> @foreach(var item in Model.NorthOrderDetails) { @Html.Partial("_NorthOrderDetails", item) } </tbody> </table>
This will create a little extra html (indexers for existing elements - is Guid , rather than int ), but it means that you have only one place to support your code.
Then in the main view add the following script for the Add button
<button type="button" id="add">Add</button>
<script> var tableBody = $('#Products tbody'); var url = '@Url.Action("Add", "YourControllerName")';
And the controller method
public PartialViewResult Add() { var model = new NorthOrderDetailscs(); return PartialView("_NorthOrderDetails"); }
Finally, if you use client-side validation (jquery-validate-unobtrusive.js) and @Html.ValidationMessageFor() with your properties, you need to re-split the validator every time you add new elements to the DOM, as described in this answer .