ASP.NET MVC - 模型绑定

ASP.NET MVC - 模型绑定 首页 / ASP.Net MVC入门教程 / ASP.NET MVC - 模型绑定

ASP.NET MVC模型绑定允许您将HTTP请求数据与模型进行映射,使用浏览器在HTTP请求中发送的数据创建.NET对象的过程。

模型绑定是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

它将显示"Add View"对话框。

链接:https://www.learnfk.comhttps://www.learnfk.com/asp.net_mvc/asp.net-mvc-model-binding.html

来源:LearnFk无涯教程网

Display Add View Dialog

如您在上面的屏幕截图中所见,已经提到了默认名称,现在,从"Template"下拉列表中选择"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

点击页面顶部的"Create New"链接,它将转到以下视图。

Create New Link

让我们输入要添加的另一位员工的数据。

Another Employee Data

单击创建按钮,您将看到新员工已添加到列表中。

New Employee Added

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

在这种情况下,只要发布的值与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模型,HTML输入字段的ID应该与Employee模型的属性名称相同,并且可以看到Visual Studio在创建视图时使用的模型的相同属性名称。

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

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

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

Request for URL

让我们单击页面顶部的"Create New"链接,它将转到以下视图。

Click Create New Link

让我们输入要添加的另一位员工的数据。

Enter Data Another Employee

现在单击"Create"按钮,您将看到使用ASP.Net MVC模型绑定将新员工添加到您的列表中。

MVC Model Binding

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

人工智能基础课 -〔王天一〕

微服务架构实战160讲 -〔杨波〕

从0开始学微服务 -〔胡忠想〕

数据分析实战45讲 -〔陈旸〕

TensorFlow快速入门与实战 -〔彭靖田〕

深入浅出计算机组成原理 -〔徐文浩〕

恋爱必修课 -〔李一帆〕

遗留系统现代化实战 -〔姚琪琳〕

计算机基础实战课 -〔彭东〕

好记忆不如烂笔头。留下您的足迹吧 :)