您的位置:首页 > 其它

MVC 模型绑定

2012-02-14 09:52 176 查看
Model binding is the process of creating .NET objects using the data sent by the browser in an Http request.

英文资料给出的定义:把Http请求传来的数据,封装成对象的过程。

默认模型绑定器:

1.按顺序从四个数据源中寻找数据:Request.Form,RouteData.Values,Request.QuerySting,Request.Files

2.原理:根据参数的名字,从数据源中寻找相同的键值对,然后赋值

3.支持类嵌套,支持数组,只要参数的类型和model的类型一致,就可以完全映射

4.可以屏蔽字段:Bind(Include="字段1,字段2"),Bind(Exclude="字段1,字段2")

5.可以手动触发:UpdateModel(),TryUpdateModel()

自定义模型绑定:

顾名思义,定义了 封装对象的过程,这个过程交给一个实现了IModelBinder接口的类;

// 例子:
public class UserContextBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
return controllerContext.HttpContext.Session["UserContext"] as UserContext;
}
}

// 在Global.asax中注册
protected void Application_Start()
{
// 注册模型绑定器
ModelBinders.Binders.Add(typeof(UserContext), new UserContextBinder());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: