gpt4 book ai didi

c# - 将 HTML 表发布到 ADO.NET DataTable

转载 作者:IT王子 更新时间:2023-10-29 03:45:45 25 4
gpt4 key购买 nike

我的 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/30094047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com