ASP.Net MVC模型绑定

ASP.NET MVC模型绑定允许您将HTTP请求数据与模型进行映射。 这是使用HTTP请求中的浏览器发送的数据创建.NET对象的过程。对于ASP.Net MVC而言,ASP.NET Web Forms开发人员大多都感到困惑,因为视图的值在到达控制类的动作方法时会如何转换为Model类,这个转换由模型绑定器完成。

模型绑定是HTTP请求和 C# 操作方法之间的良好设计桥梁。 它使开发人员可以方便地使用表单(视图)上的数据,因为POSTGET会自动传输到指定的数据模型中。 ASP.NET MVC使用默认的绑定器来完成这个场景。

我们来看一个简单的例子,在上一章的项目中添加一个“创建视图”,我们将看到如何从视图中获取这些值传到EmployeeController动作方法。

以下是POST的创建动作方法。

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

右键单击Create动作方法,然后选择添加视图…, 它将显示添加视图对话框。
如在上面的屏幕截图中看到的那样,默认的动作名字已经在输入框中了。现在从“模板”下拉列表中选择“Create”,从“模型”下拉列表中选择“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>

当用户在创建视图上输入值时,它在FormCollectionRequest.Form中都可用。可以使用这些值中的任何一个来填充视图中的员工信息。

使用下面的代码来(FormCollection)创建员工信息。参考以下代码 -

// 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 /。将收到以下输出结果 -

点击页面顶部的“Create New”链接,它将转到下面的视图。如下所示 -

输入想要添加的其他员工的数据。如下所示 -

点击创建按钮,会看到新员工被添加到列表中。如下图所示 -

在上面的示例中,从HTML视图中获取所有发布的值,然后将这些值映射到Employee属性并逐一分配它们。

在这种情况下,我们也将在发布的值与Model属性的格式不相同的情况下进行类型转换。

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

下面来看看为模型绑定所做的另一个例子。

我们需要改变Create方法的参数来接受Employee模型对象而不是FormCollection对象,如下面的代码所示。

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

现在,模型绑定的魔力取决于提供值的HTML变量的id

对于Employee模型,HTML输入字段的id应该与Employee模型的属性名称相同,可以看到Visual Studio在创建视图时使用了相同的模型属性名称。如下代码 -

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

映射将基于默认的属性名称。在这里,您会发现HTML助手方法非常有用,因为这些助手方法将生成HTML,它将具有适当的名称以使模型绑定起作用。

运行修改代码的应用程序,与上面的运行结果一样。


上一篇: ASP.Net MVC助手 下一篇: ASP.Net MVC与SQL Server数据库操作