您的位置:知识库 » .NET技术

ASP.NET MVC 2扩展点之Model Binder

作者: 麒麟  来源: 博客园  发布时间: 2010-08-02 14:07  阅读: 4186 次  推荐: 5   原文链接   [收藏]  

  Model Binder在Asp.net MVC中非常简单。简单的说就是你控制器中的Action方法需要参数数据;而这些参数数据包含在HTTP请求中,包括表单上的Value和URL中的参数等。而ModelBinder的功能就是将这些个表单上的Value和URL中的参数换成对象,然后将这些对象绑定到Action的参数上面。我简单的画了一个图,看起来会更加直观。

  在asp.net mvc中你可以写类似下面这样的代码:

[HttpPost]
public ActionResult Create()
{
Book book = new Book();
book.Title = Request.Form["Title"];
// ...
return View();
}

  但是这样的写法是非常不可取的,因为代码不容易阅读,也不易测试。再看下面的写法:

[HttpPost]
public ActionResult Create(FormCollection values)
{
Book book = new Book();
book.Title = values["Sex"];
// ...
return View();
}

  这样的写法就可以不用从Request中获取数据了,这样能满足一些情况,比直接从Request中获取数据要直观。但是如果在Action需要的数据既要来自表单上的值,又要来自URL的query string。这种情况单单FormCollection是不行的。看下面代码:

[HttpPost]
public ActionResult Create(Book book)
{
// ...
return View();
}

  上面的代码就非常的直观了,这需要我们的model binder创建一个book对象,然后直接从这个对象的属性中取值。这个book对象的数据自然也是来自Form和URL。有时候,我们的DefaultModelBinder转换的能力必经有限,也不够透明化,一些特殊和复杂的情况就需要我们自定义Model Binder。下面我讲讲如何去自定义Model Binder。

  1、首先我们定义一个Book的实体类:

public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public DateTime DatePublished { get; set; }
}

  2、自定义的model binder需要继承IModelBinder或者它的子类。数据可以从bindingContext获取。

public class BookModelBinder : IModelBinder
{

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var book = (Book)(bindingContext.Model ?? new Book());
book.Title = GetValue<string>(bindingContext, "Title");
book.Author = GetValue<string>(bindingContext, "Author");
book.DatePublished = GetValue<DateTime>(bindingContext, "DatePublished");
if (String.IsNullOrEmpty(book.Title))
{
bindingContext.ModelState.AddModelError("Title", "书名不能为空?");
}
return book;
}
private T GetValue<T>(ModelBindingContext bindingContext, string key)
{
ValueProviderResult valueResult= bindingContext.ValueProvider.GetValue(key);
bindingContext.ModelState.SetModelValue(key, valueResult);
return (T)valueResult.ConvertTo(typeof(T));
}
}

  从上面代码可以看出,自定义的ModelBinde非常的自由,可以自由的将Form上的一个key对应实体的一个属性,也可以加入一些验证的逻辑。当然还可以加入一些其他的自定义逻辑。

  3、写好BookModelBinder之后,我们只需要简单的注册一下就行了,在Global.asax添加下面代码:

ModelBinders.Binders.Add(typeof(Book), new BookModelBinder());

  总结:本文简单介绍了一下Asp.net MVC的Model Binder机制。如果叙述有问题,欢迎指正。

5
0
 

.NET技术热门文章

    .NET技术最新文章

      最新新闻

        热门新闻