小编典典

将HTML表发布到ADO.NET DataTable

c#

我的视图中有一个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表转换为ADO.NET DataTable。

如何从HTML表中提取值并将其插入ADO.NET DataTable中?

该视图基于以下模型

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; }
}

阅读 212

收藏
2020-05-19

共1个答案

小编典典

为了在回发时绑定到模型,name表单控件的属性必须与模型属性匹配。您使用foreach循环不会生成正确的名称属性。如果您检查html,则会看到多个实例

<input type="text" name="item.LeaveType" .../>

但为了绑定到模型,控件必须

<input type="text" name="LeaveDetailsList[0].LeaveType" .../>
<input type="text" name="LeaveDetailsList[1].LeaveType" .../>

等。考虑这一点的最简单方法是考虑如何LeaveTypeC#代码中访问属性的值

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),这就是控件的name属性必须是的方式。为此,您必须使用一个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>

最后,在控制器中

public ActionResult Edit(LeaveBalanceViewModel model)
{
    // iterate over model.LeaveDetailsList and save the items
}
2020-05-19