I have a HTML table as below in my View:
<table id="tblCurrentYear">
<tr>
<td>Leave Type</td>
<td>Leave Taken</td>
<td>Leave Balance</td>
<td>Leave Total</td>
</tr>
@foreach (var item in Model.LeaveDetailsList)
{
<tr>
<td>@Html.TextBoxFor(m => item.LeaveType, new { width = "100" })</td>
<td>@Html.TextBoxFor(m => item.LeaveTaken, new { width = "100" })</td>
<td>@Html.TextBoxFor(m => item.LeaveBalance, new { width = "100" })</td>
<td>@Html.TextBoxFor(m => item.LeaveTotal, new { width = "100" })</td>
</tr>
}
</table>
I want to iterate through all the html table rows and insert the values in ADO.NET DataTable.
Simple speaking, converting HTML Table to ADO.NET DataTable.
How to extract values from HTML Table and insert into ADO.NET DataTable?
The view is based on the following model
public class LeaveBalanceViewModel
{
public LeaveBalanceViewModel()
{
this.EmployeeDetail = new EmployeeDetails();
this.LeaveBalanceDetail = new LeaveBalanceDetails();
this.LeaveDetailsList = new List<LeaveBalanceDetails>();
}
public EmployeeDetails EmployeeDetail { get; set; }
public LeaveBalanceDetails LeaveBalanceDetail { get; set; }
public List<LeaveBalanceDetails> LeaveDetailsList { get; set; }
}
In order to bind to a model on post back, the
name
attributes of the form controls must match the model properties. Your use of aforeach
loop does not generate the correct name attributes. If you inspect the html you will see multiple instances ofbut in order to bind to your model the controls would need to be
etc. The easiest way to think about this is to consider how you would access the value of a
LeaveType
property inC#
codeSince your POST method will have a parameter name (say
model
), just drop the prefix (model
) and that's how the name attribute of the control must be. In order to do that you must use either afor
loop (the collection must implementIList<T>
)or use a custom
EditorTemplate
(the collection need only implementIEnumerable<T>
)In
/Views/Shared/EditorTemplates/LeaveBalanceDetails.cshtml
and then in the main view (not in a loop)
and finally, in the controller
With respect to your requirement, try this