我的 View 中有一个如下所示的 HTML 表格:
<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>
我想遍历所有 html 表行并将值插入 ADO.NET DataTable。
简单来说,将HTML Table转换为ADO.NET DataTable。
如何从 HTML 表中提取值并插入到 ADO.NET 数据表中?
View 基于以下模型
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; }
}
最佳答案
为了在回发时绑定(bind)到模型,name
表单控件的属性必须与模型属性相匹配。您对 foreach
的使用循环不会生成正确的名称属性。如果您检查 html,您将看到多个实例
<input type="text" name="item.LeaveType" .../>
但是为了绑定(bind)到您的模型,控件需要是
<input type="text" name="LeaveDetailsList[0].LeaveType" .../>
<input type="text" name="LeaveDetailsList[1].LeaveType" .../>
等考虑这一点的最简单方法是考虑如何访问 LeaveType
的值。属性(property) C#
代码
var model = new LeaveBalanceViewModel();
// add some LeaveBalanceDetails instances to the LeaveDetailsList property, then access a value
var leaveType = model.LeaveDetailsList[0].LeaveType;
由于您的 POST 方法将有一个参数名称(比如 model
),只需删除前缀(model
),这就是控件的名称属性必须的样子。为此,您必须使用 for
循环(集合必须实现 IList<T>
)
for(int i = 0; i < Model.LeaveDetailsList.Count; i++)
{
@Html.TextBoxFor(m => m.LeaveDetailsList[i].LeaveType)
....
}
或使用自定义 EditorTemplate
(集合只需要实现IEnumerable<T>
)
在/Views/Shared/EditorTemplates/LeaveBalanceDetails.cshtml
@model yourAssembly.LeaveBalanceDetails
<tr>
<td>@Html.TextBoxFor(m => m.LeaveType)</td>
....
</tr>
然后在主视图中(不在循环中)
<table>
.... // add headings (preferably in a thead element
<tbody>
@Html.EditorFor(m => m.LeaveDetailsList)
</tbody>
</table>
最后,在 Controller 中
public ActionResult Edit(LeaveBalanceViewModel model)
{
// iterate over model.LeaveDetailsList and save the items
}
关于c# - 将 HTML 表发布到 ADO.NET DataTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297441/