鍍金池/ 教程/ C#/ ASP.Net MVC助手
ASP.Net MVC簡(jiǎn)介
ASP.Net MVC過(guò)濾器
ASP.Net MVC視圖
ASP.Net MVC安全
ASP.Net MVC手腳架
ASP.Net MVC控制器
ASP.Net MVC與SQL Server數(shù)據(jù)庫(kù)操作
ASP.Net MVC NuGet包管理
ASP.Net MVC入門(mén)程序
ASP.Net MVC Razor
ASP.Net MVC Bootstrap
ASP.Net MVC單元測(cè)試
ASP.Net MVC動(dòng)作
ASP.Net MVC模式
ASP.Net MVC選擇器
ASP.Net MVC開(kāi)發(fā)環(huán)境配置
ASP.Net MVC生命周期
ASP.Net MVC模型綁定
ASP.Net MVC自托管(本地主機(jī)部署)
ASP.Net MVC驗(yàn)證
ASP.Net MVC緩存
ASP.Net MVC數(shù)據(jù)模型
ASP.Net MVC路由
ASP.Net MVC教程
ASP.Net MVC助手
ASP.Net MVC數(shù)據(jù)注解
ASP.Net MVC Web API

ASP.Net MVC助手

在ASP.Net Web表單中,開(kāi)發(fā)人員正在使用工具箱來(lái)在任何特定的頁(yè)面上添加控件。 但是,在ASP.NET MVC應(yīng)用程序中,沒(méi)有工具箱可用于在視圖上拖放HTML控件。 在ASP.NET MVC應(yīng)用程序中,如果想創(chuàng)建一個(gè)視圖,它應(yīng)該包含HTML代碼。 所以那些剛接觸MVC的開(kāi)發(fā)者,特別是在網(wǎng)頁(yè)表單的背景下,發(fā)現(xiàn)這個(gè)有點(diǎn)難。

為了克服這個(gè)問(wèn)題,ASP.NET MVC提供了HtmlHelper類,它包含不同的方法來(lái)幫助你編程創(chuàng)建HTML控件。 所有的HtmlHelper方法都會(huì)生成HTML并以字符串形式返回結(jié)果。 最終的HTML是由這些函數(shù)在運(yùn)行時(shí)生成的。 HtmlHelper類用于生成UI,不應(yīng)該在控制器或模型中使用。

有不同類型的幫手方法。

  • Createinputs - 為文本框和按鈕創(chuàng)建輸入。
  • Createlinks - 創(chuàng)建基于來(lái)自路由表的信息的鏈接。
  • Createforms - 創(chuàng)建表單標(biāo)簽,可以回發(fā)到動(dòng)作,或回發(fā)到另一個(gè)控制器上的操作。

如果有看過(guò)前面視圖教程文章中(項(xiàng)目:MVCSimpleApp) EmployeeController控制器的Index動(dòng)作生成的視圖,將看到以Html開(kāi)始的操作符前綴,如Html.ActionLinkHtml.DisplayNameFor等,如下面的代碼所示。

@model IEnumerable<MVCSimpleApp.Models.Employee>
@{
   Layout = null;
} 

<!DOCTYPE html>
<html>
   <head>
      <meta name = "viewport" content = "width = device-width" />
      <title>Index</title>
   </head>

   <body>
      <p>
         @Html.ActionLink("Create New", "Create")
      </p>

      <table class = "table">
         <tr>
            <th>
               @Html.DisplayNameFor(model => model.Name)
            </th>

            <th>
               @Html.DisplayNameFor(model => model.JoiningDate)
            </th>

            <th>
               @Html.DisplayNameFor(model => model.Age)
            </th>

            <th></th>
         </tr>

         @foreach (var item in Model) {
            <tr>
               <td>
                  @Html.DisplayFor(modelItem => item.Name)
               </td>

               <td>
                  @Html.DisplayFor(modelItem => item.JoiningDate)
               </td>

               <td>
                  @Html.DisplayFor(modelItem => item.Age)
               </td>

               <td>
                  @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                  @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                  @Html.ActionLink("Delete", "Delete", new { id = item.ID })
               </td>
            </tr>
         }

      </table>
   </body>
</html>

這個(gè)HTML是從ViewPage基類繼承的一個(gè)屬性。所以,它在所有的視圖中都可用,并返回一個(gè)名為HTMLHelper的實(shí)例。

我們來(lái)看看一個(gè)簡(jiǎn)單的例子,讓用戶可以編輯員工信息。 因此,此編輯操作將使用大量不同的HTML助手。

如果看上面的代碼,會(huì)在最后部分看到下面的HTML Helper方法 -

@Html.ActionLink("Edit", "Edit", new { id = item.ID })

ActionLink助手中,第一個(gè)參數(shù)是“Edit”鏈接,第二個(gè)參數(shù)是控制器中的動(dòng)作方法,也是“Edit”,第三個(gè)參數(shù)ID是要編輯的員工編號(hào)。

我們通過(guò)添加靜態(tài)列表來(lái)更改EmployeeController類,并使用以下代碼更改索引操作。

public static List<Employee> empList = new List<Employee>{
   new Employee{
      ID = 1,
      Name = "Allan",
      JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
      Age = 23
   },

   new Employee{
      ID = 2,
      Name = "Carson",
      JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
      Age = 45
   },

   new Employee{
      ID = 3,
      Name = "Carson",
      JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
      Age = 37
   },

   new Employee{
      ID = 4,
      Name = "Laura",
      JoiningDate = DateTime.Parse(DateTime.Today.ToString()),
      Age = 26
   },

};

public ActionResult Index(){
   var employees = from e in empList
   orderby e.ID
   select e;
   return View(employees);
}

下面來(lái)更新編輯操作。您將看到兩個(gè)編輯操作,一個(gè)用于GET,一個(gè)用于POST。這里更新GET的編輯操作,其中只有參數(shù)中的Id,如下面的代碼所示。

// GET: Employee/Edit/5
public ActionResult Edit(int id){
   List<Employee> empList = GetEmployeeList();
   var employee = empList.Single(m => m.ID == id);
   return View(employee);
}

現(xiàn)在,我們知道有編輯的動(dòng)作,但是沒(méi)有任何對(duì)應(yīng)此動(dòng)作的視圖。 所以還需要添加一個(gè)視圖(View)。 為此,請(qǐng)右鍵單擊Edit操作,然后選擇添加視圖。從“模板”下拉列表中選擇Edit,從“模型”下拉列表中選擇“Employee” -

以下是Edit視圖中的默認(rèn)實(shí)現(xiàn)。參考以下示例代碼 -

@model MVCSimpleApp.Models.Employee

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Employee</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.ID)

            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.JoiningDate, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.JoiningDate, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.JoiningDate, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

Html.BeginForm非常有用,因?yàn)樗鼓軌蚋腢RL,更改方法等。

在上面的代碼中,看到另一個(gè)HTML助手:@ HTML.HiddenFor,它用于生成隱藏的字段。

MVC框架足夠聰明地發(fā)現(xiàn)這個(gè)ID字段在模型類中,因此它需要防止被編輯編修改,這就是為什么它被標(biāo)記為隱藏字段的原因。

Html.LabelFor HTML助手在屏幕上創(chuàng)建標(biāo)簽。如果在進(jìn)行更改時(shí)錯(cuò)誤地輸入了任何內(nèi)容,則Html.ValidationMessageFor助手將顯示正確的錯(cuò)誤消息。

還需要更改POST的編輯操作,需要更新員工信息時(shí),它就會(huì)調(diào)用這個(gè)動(dòng)作。參考以下代碼 -

        // POST: Employee/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                List<Employee> empList = GetEmployeeList();
                var employee = empList.Single(m => m.ID == id);
                if (TryUpdateModel(employee))
                {
                    //To Do:- database code
                    return RedirectToAction("Index");
                }
                return View(employee);
            }
            catch
            {
                return View();
            }
        }

讓我們運(yùn)行這個(gè)應(yīng)用程序,并請(qǐng)求以下URL:http://localhost:64466/Employee員工。將會(huì)看到以下輸出。

點(diǎn)擊任何特定員工的編輯鏈接,以點(diǎn)擊員工編號(hào)為1編輯鏈接為示例,您將看到以下視圖顯示結(jié)果。

將年齡從23歲改為29歲,然后點(diǎn)擊“保存”按鈕,然后會(huì)在Index視圖中看到更新的年齡。