Authorization [ˌɔ:θərəˈzeɪʃn] 授权
当创建一个新的模型绑定器时,我们需要告知ASP.NET MVC框架存在一个新的模型绑定器以及何时使用它。
一、 模型扩展
1 、把请求数据转换为模型
将请求数据(比如表单数据、查询字符串数据或路由信息)转换为模型的过程称为模型绑定。
模型绑定的过程分为两个阶段:
通过使用值提供器理解数据的来源
使用这些值创建/更新模型对象(通过使用模型绑定器)
(1)、使用值提供器解析请求数据
值提供器:访问能够在模型绑定过程中正确使用的信息。
(2)、创建带有模型绑定器的模型 IModelBinder
从值提供器系统中获取值,并利用获取的值创建新模型或者填充已有模型。ASP.NET MVC中默认模型绑定器可以对传统类、集合类、列表、数组甚至字典进行模型绑定。
不支持不可变对象,对象的初始值必须通过构造函数设置,之后不能改变。
示例1:Point类是不可变的,因此我们必须使用它的值构造一个新实例
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Web.Mvc;
namespace WebApplication3.Areas.ModelBinder.Utility
{
public class PointModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
//值提供器
var valueProvider = bindingContext.ValueProvider;
//从值提供器上获取值,创建新模型
int x = (int)valueProvider.GetValue("X").ConvertTo(typeof(int));
int y = (int)valueProvider.GetValue("Y").ConvertTo(typeof(int));
return new Point(x,y);
}
}
}
当创建一个新的模型绑定器时,我们需要告知ASP.NET MVC框架存在一个新的模型绑定器以及何时使用它。
可以使用[ModelBinder]特性来装饰绑定类,也可以在ModelBinders.Binders的全局列表中注册新的模型绑定器。
using System.Drawing;
using System.Web.Mvc;
using WebApplication3.Areas.ModelBinder.Utility;
namespace WebApplication3.Areas.ModelBinder
{
public class ModelBinderAreaRegistration : AreaRegistration
{
public override string AreaName { get { return "ModelBinder"; } }
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"ModelBinder_default",
"ModelBinder/{action}/{id}",
new { controller = "ModelBinder", action = "Index", id = UrlParameter.Optional }
);
//ModelBinders.Binders全局列表中注册新的模型绑定器
ModelBinders.Binders.Add(typeof(Point), new PointModelBinder());
}
}
}
控制器、视图如下:
using System;
using System.Drawing;
using System.Web.Mvc;
namespace WebApplication3.Areas.ModelBinder.Controllers
{
public class ModelBinderController : Controller
{
public ActionResult Index()
{
return View(new Point(0, 0));
}
[HttpPost]
public ActionResult Index(Point pt)
{
//在本示例中,默认情况下客户端端验证是关闭的,以便您可