将HTML表发布到ADO.NET DataTable

将HTML表发布到ADO.NET DataTable

我的视图中有一个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; }

}


肥皂起泡泡
浏览 683回答 2
2回答

九州编程

为了在回发时绑定到模型,name表单控件的属性必须与模型属性匹配。使用foreach循环不会生成正确的名称属性。如果您检查html,您将看到多个实例<input type="text" name="item.LeaveType" .../>但为了绑定到您的模型,控件需要<input type="text" name="LeaveDetailsList[0].LeaveType" .../><input type="text" name="LeaveDetailsList[1].LeaveType" .../>考虑这个问题最简单的方法是考虑如何LeaveType在C#代码中访问属性的值var model = new LeaveBalanceViewModel();// add some LeaveBalanceDetails instances to the LeaveDetailsList property, then access a valuevar leaveType = model.LeaveDetailsList[0].LeaveType;由于您的POST方法将具有参数名称(例如model),只需删除前缀(model),这就是控件的name属性必须如何。为了做到这一点,你必须使用一个for循环(集合必须实现IList<T>)for(int i = 0; i < Model.LeaveDetailsList.Count; i++){&nbsp; &nbsp; @Html.TextBoxFor(m => m.LeaveDetailsList[i].LeaveType)&nbsp; &nbsp; ....}或使用自定义EditorTemplate(集合只需要实现IEnumerable<T>)在 /Views/Shared/EditorTemplates/LeaveBalanceDetails.cshtml@model yourAssembly.LeaveBalanceDetails<tr>&nbsp; &nbsp; <td>@Html.TextBoxFor(m => m.LeaveType)</td>&nbsp; &nbsp; ....</tr>然后在主视图中(不在循环中)<table>&nbsp; &nbsp; .... // add headings (preferably in a thead element&nbsp; &nbsp; <tbody>&nbsp; &nbsp; &nbsp; &nbsp; @Html.EditorFor(m => m.LeaveDetailsList)&nbsp; &nbsp; </tbody></table>最后,在控制器中public ActionResult Edit(LeaveBalanceViewModel model){&nbsp; &nbsp; // iterate over model.LeaveDetailsList and save the items}
打开App,查看更多内容
随时随地看视频慕课网APP