亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將HTML表發布到ADO.NET DataTable

將HTML表發布到ADO.NET DataTable

肥皂起泡泡 2019-05-21 15:47:22
將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; }}
查看完整描述

2 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

為了在回發時綁定到模型,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 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

}


查看完整回答
反對 回復 2019-05-21
  • 2 回答
  • 0 關注
  • 715 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號