• ASP.NET MVC2之Model Binder


    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["Title"];
    // ...
    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; }
    }

      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")+"www";//这里在获取到表单的Title信息后随便追加个"www",用来测试的
    book.Author = GetValue<string>(bindingContext, "Author");
    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添加下面代码:

        protected void Application_Start()
            {
                ModelBinders.Binders.Add(typeof(Book), new BookModelBinder());
                AreaRegistration.RegisterAllAreas();

                RegisterRoutes(RouteTable.Routes);
            }

      4、View中的表单代码:

        <form action="Show" method="post">
                书名:<input type="text" name="Title"/><br />
                作者:<input type="text" name="Author" /><br />
                <input type="submit" value="提交" />
            </form>

      5、Controller中对应的Action的代码:

       public ActionResult Show(Book book)
            {
                return View();
            }

      在Action中可以通过添加断点来查看book对象中的信息,是通过ModelBinder来进行绑定信息的。

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

  • 相关阅读:
    c语言寒假大作战02
    C语言寒假大作战01
    C语言I作业12
    C语言I博客作业11
    C语言I博客作业10
    C语言ll作业01
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
  • 原文地址:https://www.cnblogs.com/tianguook/p/3989497.html
Copyright © 2020-2023  润新知