@Html.EditorForModel()用法

MSDN上對@Html.EditorForModel()的解釋是Returns an HTML input element for each property in the model, using additional view data, 即使用另外一個View來爲本VIew中Model每一個屬性返回一個Html 輸入元素。

以Student類爲例,實現顯示出數據庫表中所有的學生信息的結果,具體用法如下:

1, 在Student文件夾中的Index.cshtml中放入@Html.EditorForModel(),代碼如下:

@model IEnumerable<MVC_DeleteMultiRow.Models.Student>
@{
    ViewBag.Title = "Index";
}
<h2>Employee List</h2>
@using (Html.BeginForm("Delete", "Student", FormMethod.Post))
{
    <table border="1">
        <thead>
            <tr>
                <th>
                    <input type="checkbox" name="checkAll" id="checkAll">
                </th>
                <th>
                    Name
                </th>
                <th>
                    Gender
                </th>
                <th>
                    Email
                </th>
            </tr>
        </thead>
        <tbody>
           <span style="background-color: rgb(255, 255, 51);"> <span style="background-color: rgb(255, 255, 102);">@Html.EditorForModel()<</span>/span>
        </tbody>
    </table>
    <input type="submit" id="btnSubmit" name="btnSubmit" value="Delete Selected students"/>
}


2,在View文件夾下的Shared文件夾下新建一個文件夾EditorTemplates,在EditorTemplates文件夾中新建一個View,文件名爲Student.cshtml,在此文件中放入想顯示的html元素及model的屬性,本例的代碼如下:

@model MVC_DeleteMultiRow.Models.Student 
<h2>Student</h2>
<tr>
    <td>
        <input type="checkbox" name="employeeIdsToDelete" id="employeeIdsToDelete" value="@Model.ID">
    </td>
    <td>
        @Model.Name 
    </td>  
    <td>
        @Model.Gender
    </td>
    <td>
        @Model.Email 
    </td>
</tr>
這樣就可以實現我們想要的效果了,文件夾目錄以及頁面上實現的效果分別如下圖:



如果把@Html.EditorForModel()替換成下面的代碼也可以實現同樣的效果:

    @foreach(var item in Model)
        {
            <tr>
              <td>
                <input type="checkbox" name="employeeIdsToDelete" id="employeeIdsToDelete" value="@item.ID">
              </td>
              <td>
                  @item.Name
              </td>
              <td>
                  @item.Name
              </td>
              <td>
                  @item.Name
              </td>
            </tr>
        }













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章