ASP.NET MVC模型绑定的6个建议

  ASP.NET MVC中的Model Binding使用起来非常简单,本文总结了关于在MVC项目中更好使用Model Binding的一些建议.供大家学习、参考.    ASP.NET MVC中的Model Binding使用起来非常简单.你的Action方法需要数据,在传入的HTTP请求中携带着你需要的数据,数据可以在请求的表单数据中,还可能在你的 URL地址本身中.通过DefaultModelBinder,可以神奇地将表单中的数据和路由中的数据转换到对象中.Model Binder使得你的控制器代码可以干净地从请求以及关联的环境中分离出来.
    这里有一些关于在MVC项目中更好使用Model Binding的建议.
    Tip#1:最好使用Model Binding而不是Request.Form
    如果你的Action像下面这样:
    1.[AcceptVerbs(HttpVerbs.Post)]
    2.
    3.public ActionResult Create()
    4.
    5.{
    6.
    7.    Recipe recipe = new Recipe();
    8.
    9.    recipe.Name = Request.Form[“Name”];
    10.
    11.
    12.
    13.    // ...
    14.
    15.
    16.
    17.    return View();
    18.
    19.}
    就不对了.这些属性使得你的Action很难读而且更难以测试,Model Binder可以帮你从Request和HttpContext中摆脱出来.比如,你可以使用FormCollection类型的参数来代替上面的代码:
    1.public ActionResult Create(FormCollection values)
    2.
    3.{
    4.
    5.    Recipe recipe = new Recipe();
    6.
    7.    recipe.Name = values[“Name”];
    8.
    9.
    10.
    11.    // ...
    12.
    13.
    14.
    15.    return View();
    16.
    17.}
    使用FormCollection你可以不必再深入到Request对象,这样,有时候你就可以使用低层次的控制了.但是,如果你的数据来自Request.Form,或者URL请求参数,你可以通过Model Binding来完成它的魔术.
    1.[AcceptVerbs(HttpVerbs.Post)]
    2.
    3.public ActionResult Create(Recipe newRecipe)
    4.
    5.{
    6.
    7.    // ...
    8.
    9.
    10.
    11.    return View();
    12.
    13.}
    在这个例子中,Model Binder将会帮你创建newRecipe对象,并且使用从Request中获得获得的数据来填充它,真的是魔术.有许多的途径允许你定制绑定的处理过 程,使用白名单,黑名单,前缀,以及接口,更多的控制还允许你通过UpdateModel和TryUpdateModel方法进行,只是要注意无意的绑 定.看一看Justin Etheredge的文章Think Before You Bind.