使用ModelBinder处理Actin实体类型参数

一,关于DefaultModelBinder(无需额外代码就从表单提交的字符串转换实体类)

比如一个Action要传入Person类型的参数,而不是普通的字符串。

        public ActionResult AddPerson(Person model)
        {
            return View(model);
        }

MVC其实已经做了处理,如果html表单中的元素和Person类中属性名称一样,就会自动生成一个Person类,然后赋值给对应的属性字段

 public class Person
    {
        public string name { get; set; }
        public string age { get; set; }
        public string sex { get; set; }
        public Company company { get; set; }
    }

    public class Company
    {
        public string name { get; set; }
        public string address { get; set; }
    }

Html表单形式。

其中Company又是一个实体类型属性,使用company.name的表单名称来指定

<form action="/home/addperson">
<input id="name" name="name" />
<input id="age" name="age" />
<input id="company.name" name="company.name"/>
<input type="submit" value="submit" />
</form>

这样在传入Action的时候就会自动生成Person类实例

        public ActionResult AddPerson(Person model)
        {
            return View(model);
        }

内部的实现的原理是因为有个DefaultModelBinder,这是一个默认的Model绑定转换类

二。实现一个自定义的Modelbinder并且在controller中使用

如果要实现一个自定义的ModelBinder必须要继承一个接口IModelBinder,实现这个方法BindModel

    public class PersonBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string name = controllerContext.RequestContext.HttpContext.Request["name"];
            string age = controllerContext.RequestContext.HttpContext.Request["age"];
            Person p = new Person() { name = name, age=age };
            return p;
        }
    }

在Controller中要指定才能使用,这样在处理到这个Action的时候会先去PersonBinder 中处理接收的参数

        public ActionResult AddPerson([ModelBinder(typeof(PersonBinder))]Person model)
        {
            return View(model);
        }

三。在MVC中添加新的默认modelbinder

如何让自定义的ModelBinder默认执行,如果一个Modelbinder可以针对每个action都适用

比如可以自定义一个Modelbinder对所有输入的字符串都进行Trim()。最好的方式是让这个ModelBinder在每个Action中都默认执行,而不是需要每次都在

Controller中显式的指定。

这个Modelbinder需要继承DefaultModelBinder

 public class StringTrimBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = base.BindModel(controllerContext, bindingContext);
            if (value is string)
            {
                return value.ToString().Trim();
            }
            else
            {
                return value;
            }
        }
    }

在Global。asax文件中

 protected void Application_Start()
  {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            
            ModelBinders.Binders.Add(typeof(string), new StringTrimBinder());
  }

这样在Controller中无需指定Modelbinder就可以执行

        public ActionResult AddPerson(Person model)
        {
            return View(model);
        }
原文地址:https://www.cnblogs.com/zjypp/p/2586409.html