本文转载自haiziguo
Asp.net mvc中的模型绑定,或许大家经常用,但是具体说他是怎么一回事,可能还是会有些陌生,那么,本文就带你理解模型绑定。为了理解模型绑定,本文会先给出其定义,然后对通过比,来得出使用模型绑定的方便。最后简单的模拟一下自定义模型绑定,让大家对模型绑定有进一步的认识。
mvc framework中有一种技术,他就是模型绑定:
使用 被浏览器发送的http请求里面数据 来创建.net对象的过程。接下来就让我们来看看模型绑定的好处。
二、模型绑定好处
第二部分,我们通过不使用模型绑定和使用模型绑定的两种效果的对比,得出模型绑定的优势。那么接下来先让我们来模拟一个没有模型绑定的环境。
2.1没有模型绑定的环境
让我们先来模拟一个没有模型绑定的环境,主要是让用户填写的信息传达到Controller中,然后经过加工后显示到View上(通常情况下我们是得到model后直接把model作为一个模型实体,提交到数据库了,为了简单起见,我只是把得到的模型信息显示出来)。先利用vs2010新建一个mvc3项目,在models文件夹中新建一个Person类,代码如下:
using System.Web.Mvc; using System.ComponentModel.DataAnnotations; public class Person { [Display(Name="编号")] public String Id { get; set; } [Display(Name = "姓:")] public string FirstName { get; set; } [Display(Name = "名:")] public string LastName { get; set; } }
然后在views文件夹里面添加一个Example0视图,视图的代码如下:
<form method="post"/> <table cellpadding="5" cellspacing="0" width="50%"> <tr> <td align="right" nowrap="nowrap" width="15%"> 编号 :</td> <td> <input name="Id" type="text" /></td> </tr> <tr> <td align="right" nowrap="nowrap" width="15%"> 姓 :</td> <td> <input name="FirstName" type="text" /></td> </tr> <tr> <td align="right" nowrap="nowrap" width="15%">名 :</td> <td><input name="LastName" type="text"/></td> </tr> <tr> <td align="left" colspan="2" nowrap="nowrap" width="15%"> <input id="Submit1" type="submit" value="提交" /></td> </tr> <tr> <td align="left" colspan="2"> <strong> @ViewBag.StatusMessage </strong> </td> </tr> </table>
然后在Controllers文件夹里面新建一个HomeController,添加如下代码:
public ActionResult Example0() { Person p = new Person(); if (Request.Form.Count > 0) { p.Id = Request.Form["Id"]; p.FirstName = Request.Form["FirstName"]; p.LastName = Request.Form["LastName"]; TryUpdateModel(p); ViewBag.StatusMessage = "欢迎您!" + p.FirstName + p.LastName + "您的编号是" + p.Id + "!"; } return View(); }
然后配置路由,使上面的Example0页面为起始项,运行并填入数据,结果为:
点击提交按钮。显示如下结果:
从Controller的代码来看,我们主要是使用Request.Form.Count 来判断是否接收到了值,然后再一一的遍历我们想要得到的值,最后也算得到了。下面让我们来看一下使用模型绑定的效果:
2.2使用模型绑定
然后在Views/Home文件夹添加一个Example2.cshtml。代码如下:
form method="post"> <table cellpadding="5" cellspacing="0" width="50%"> <tr> <td align="right" nowrap="nowrap" width="15%"> 编号 :</td> <td> <input name="Id" type="text" /></td> </tr> <tr> <td align="right" nowrap="nowrap" width="15%"> 姓 :</td> <td> <input name="FirstName" type="text" /></td> </tr> <tr> <td align="right" nowrap="nowrap" width="15%">名 :</td> <td><input name="LastName" type="text"/></td> </tr> <tr> <td align="left" colspan="2" nowrap="nowrap" width="15%"> <input id="Submit1" type="submit" value="提交" /></td> </tr> <tr> <td align="left" colspan="2"> <strong> @ViewBag.StatusMessage </strong> </td> </tr> </table>