ASP.NET MVC - 模型绑定

ASP.NET MVC模型绑定允许您使用模型映射HTTP请求数据.它是使用浏览器在HTTP请求中发送的数据创建.NET对象的过程.不熟悉ASP.Net MVC的ASP.NET Web Forms开发人员大多混淆了View的值在到达Controller类的Action方法时如何转换为Model类,因此这个转换由Model绑定器完成.

模型绑定是HTTP请求和C#操作方法之间设计良好的桥梁.它使开发人员可以轻松处理表单(视图)上的数据,因为POST和GET会自动转移到您指定的数据模型中. ASP.NET MVC使用默认绑定器在场景后面完成此操作.

让我们看一个简单的例子,我们在上一章的项目中添加一个'Create View',我们将看到如何从View到EmployeeController操作方法获取这些值.

以下是POST的Create Action方法.

// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
   try{
      // TODO: Add insert logic here
      return RedirectToAction("Index");
   }catch{
      return View();
   }
}


右键单击Create Action方法并选择Add View ...

Right-click Create Action

它将显示"添加视图"对话框.

显示添加视图对话框

正如您在上面的屏幕截图中看到的,默认名称已经提到了.现在从Model下拉列表中选择Create,从Model类下拉列表中选择Employee.

您将在Create.cshtml视图中看到默认代码.

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

<!DOCTYPE html>
<html>
   <head>
      <meta name = "viewport" content = "width = device-width" />
      <title>Create</title>
   </head>
	
   <body>
      @using (Html.BeginForm()){
         @Html.AntiForgeryToken()
         <div class = "form-horizontal">
            <h4>Employee</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
				
            <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 = "Create" class = "btn btn-default"/>
               </div>
            </div>
				
         </div>
      }
		
      <div>
         @Html.ActionLink("Back to List", "Index")
      </div>
		
   </body>
</html>


当用户在Create View上输入值时,它在FormCollection和Request.Form中可用.我们可以使用这些值中的任何一个来填充视图中的员工信息.

让我们使用以下代码使用FormCollection创建Employee.

// POST: Employee/Create
[HttpPost]
public ActionResult Create(FormCollection collection){
   try {
      Employee emp = new Employee();
      emp.Name = collection["Name"];
      DateTime jDate;
      DateTime.TryParse(collection["DOB"], out jDate);
      emp.JoiningDate = jDate;
      string age = collection["Age"];
      emp.Age = Int32.Parse(age);
      empList.Add(emp);
      return RedirectToAction("Index");
   }catch {
      return View();
   }
}


运行此应用程序并请求此URL http://localhost:63004/Employee/.您将收到以下输出.

Localhost Employee Output

点击页面顶部的"新建"链接,它将转到以下视图.

创建新链接

让我们为您要添加的其他员工输入数据.

另一个员工数据

点击"创建"按钮,您会看到新员工已添加到列表中.

新员工已添加

在上面的示例中,我们从HTML视图中获取所有发布的值,然后映射这些值值为Employee属性并逐个赋值.

在这种情况下,我们也将在发布值ar的任何地方进行类型转换e与Model属性的格式不同.

这也称为手动绑定,对于简单和小型数据模型,这种类型的实现可能不是那么糟糕.但是,如果你有庞大的数据模型并且需要大量的类型转换,那么我们可以利用ASP.NET MVC模型绑定的强大功能和易用性.

让我们来看看在我们为模型绑定做的相同示例中.

我们需要更改Create Method的参数以接受Employee Model对象而不是FormCollection,如下面的代码所示.

// POST: Employee/Create
[HttpPost]
public ActionResult Create(Employee emp){
   try{
      empList.Add(emp);
      return RedirectToAction("Index");
   }catch{
      return View();
   }
}


现在模型绑定的神奇之处取决于提供值的HTML变量的id.

对于我们的Employee Model,HTML输入字段的id应该与Employee Model的Property name相同,您可以看到Visual Studio在创建时使用了相同的模型属性名称一个视图.

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

默认情况下,映射将基于属性名称.这是我们发现HTML帮助器方法非常有用的地方,因为这些辅助方法将生成HTML,它将具有适当的名称以使模型绑定起作用.

运行此应用程序并请求URL http://localhost:63004/Employee/.您将看到以下输出.

URL请求

让我们点击页面顶部的"新建"链接,它将转到以下视图.

点击创建新链接

让我们为我们想要添加的其他员工输入数据.

输入数据另一名员工

现在单击"创建"按钮,您将看到使用ASP.Net MVC模型绑定将新员工添加到列表中./p> MVC Model Binding