(推荐)第15章 扩展ASP.NET MVC (IModelBinder、过滤器)

本文详细介绍了如何扩展ASP.NET MVC的模型,包括使用IModelBinder进行模型绑定,如处理不可变对象,以及验证模型。同时,文章探讨了视图和控制器的扩展,特别是控制器中的操作选择、操作过滤器如身份验证和异常处理。
摘要由CSDN通过智能技术生成
Authorization [ˌɔ:θərəˈzeɪʃn] 授权

一、 模型扩展

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)
        {
            //在本示例中,默认情况下客户端端验证是关闭的,以便您可
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tiz198183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值