ASP.Net MVC助手

在ASP.Net Web表单中,开发人员正在使用工具箱来在任何特定的页面上添加控件。 但是,在ASP.NET MVC应用程序中,没有工具箱可用于在视图上拖放HTML控件。 在ASP.NET MVC应用程序中,如果想创建一个视图,它应该包含HTML代码。 所以那些刚接触MVC的开发者,特别是在网页表单的背景下,发现这个有点难。

为了克服这个问题,ASP.NET MVC提供了HtmlHelper类,它包含不同的方法来帮助你编程创建HTML控件。 所有的HtmlHelper方法都会生成HTML并以字符串形式返回结果。 最终的HTML是由这些函数在运行时生成的。 HtmlHelper类用于生成UI,不应该在控制器或模型中使用。

有不同类型的帮手方法。

  • Createinputs - 为文本框和按钮创建输入。
  • Createlinks - 创建基于来自路由表的信息的链接。
  • Createforms - 创建表单标签,可以回发到动作,或回发到另一个控制器上的操作。

如果有看过前面视图教程文章中(项目:MVCSimpleApp) EmployeeController控制器的Index动作生成的视图,将看到以Html开始的操作符前缀,如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>

这个HTML是从ViewPage基类继承的一个属性。所以,它在所有的视图中都可用,并返回一个名为HTMLHelper的实例。

我们来看看一个简单的例子,让用户可以编辑员工信息。 因此,此编辑操作将使用大量不同的HTML助手。

如果看上面的代码,会在最后部分看到下面的HTML Helper方法 -

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

ActionLink助手中,第一个参数是“Edit”链接,第二个参数是控制器中的动作方法,也是“Edit”,第三个参数ID是要编辑的员工编号。

我们通过添加静态列表来更改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);
}

下面来更新编辑操作。您将看到两个编辑操作,一个用于GET,一个用于POST。这里更新GET的编辑操作,其中只有参数中的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);
}

现在,我们知道有编辑的动作,但是没有任何对应此动作的视图。 所以还需要添加一个视图(View)。 为此,请右键单击Edit操作,然后选择添加视图。从“模板”下拉列表中选择Edit,从“模型”下拉列表中选择“Employee” -

以下是Edit视图中的默认实现。参考以下示例代码 -

@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非常有用,因为它使您能够更改URL,更改方法等。

在上面的代码中,看到另一个HTML助手:@ HTML.HiddenFor,它用于生成隐藏的字段。

MVC框架足够聪明地发现这个ID字段在模型类中,因此它需要防止被编辑编修改,这就是为什么它被标记为隐藏字段的原因。

Html.LabelFor HTML助手在屏幕上创建标签。如果在进行更改时错误地输入了任何内容,则Html.ValidationMessageFor助手将显示正确的错误消息。

还需要更改POST的编辑操作,需要更新员工信息时,它就会调用这个动作。参考以下代码 -

        // 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();
            }
        }

让我们运行这个应用程序,并请求以下URL:http://localhost:64466/Employee员工。将会看到以下输出。

点击任何特定员工的编辑链接,以点击员工编号为1编辑链接为示例,您将看到以下视图显示结果。

将年龄从23岁改为29岁,然后点击“保存”按钮,然后会在Index视图中看到更新的年龄。


上一篇: ASP.Net MVC数据模型 下一篇: ASP.Net MVC模型绑定