自定义模型绑定系统

一、创建自定义的值提供器

1.通过创建自定义的值提供器,我们可以把自己的数据源添加到模型绑定过程。而值提供器需要实现IValueProvider接口。下面是此接口的定义

namespace System.Web.Mvc
{
    /// <summary>
    /// Defines the methods that are required for a value provider in ASP.NET MVC.
    /// </summary>
    public interface IValueProvider
    {
        /// <summary>
        /// Determines whether the collection contains the specified prefix.
        /// </summary>
        /// <param name="prefix">The prefix to search for.</param>
        /// <returns>true if the collection contains the specified prefix; otherwise, false.</returns>
        bool ContainsPrefix(string prefix);

        /// <summary>
        /// Retrieves a value object using the specified key.
        /// </summary>
        /// <param name="key">The key of the value object to retrieve.</param>
        /// <returns>The value object for the specified key. If the exact key is not found, null.</returns>
        ValueProviderResult GetValue(string key);
    }
}

ContainsPrefix方法由模型绑定器调用,以确定这个值提供器是否可以解析给定前置的数据。

GetValue方法返回给定数据键的值,或者在值提供器无法得到合适的数据时,返回"null".

我们定义一个自定义的值提供器

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication4.Models
{
    public class CurrentTimeValueProvider : IValueProvider
    {
        public bool ContainsPrefix(string prefix)
        {
            return string.Compare("CurrentTime", prefix, true) == 0;
        }

        public ValueProviderResult GetValue(string key)
        {
            return ContainsPrefix(key) ? new ValueProviderResult(DateTime.Now, null, CultureInfo.InvariantCulture) : null;
        }
    }
}

2.怎么把自定义的值提供器注册给应用程序。我们需要创建一个工厂类,以创建值提供器的实例。这个类派生于抽象类ValueProviderFactory.这个抽象类的定义如下:

namespace System.Web.Mvc
{
    public abstract class ValueProviderFactory
    {
        public abstract IValueProvider GetValueProvider(ControllerContext controllerContext);
    }
}

定义一个自定义值提供器工厂:

    public class CurrentTimeValueProviderFactory:ValueProviderFactory
    {

        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            return new CurrentTimeValueProvider();
        }
    }

3.最后一步,我们在应用程序中注册这个工厂类。

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            ValueProviderFactories.Factories.Insert(0, new CurrentTimeValueProviderFactory());

            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }


二、创建依赖性感知的模型绑定器。

通过对DefaultModelBidner类进行派生,并重写其CreateModel方法,以创建一个DI感知的绑定器。

1、创建一个自定义的DI感知模型绑定器,这个类使用应用程序范围的依赖性解析器来创建模型对象,并在必要的时候回退到基类的实现中。

   public class DIModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            //添加DI智能感知
            return DependencyResolver.Current.GetService(modelType) ?? base.CreateModel(controllerContext, bindingContext, modelType);
        }
    }

2、我们必须把我定义的DI感知绑定器注册为应用程序的默认模型绑定器,可以再Global.asax的Application_Start方法中注册。

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            //ValueProviderFactories.Factories.Insert(0, new CurrentTimeValueProviderFactory());
            ValueProviderFactories.Factories.Add( new CurrentTimeValueProviderFactory());
            //把我們自定義的模型綁定器註冊為應用程序默認的模型綁定器
            ModelBinders.Binders.DefaultBinder = new DIModelBinder();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }


三、创建自定义的模型绑定器

提供IModelBinder接口,可以创建自定义的模型绑定器。

namespace System.Web.Mvc
{
    public interface IModelBinder
    {
        object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);
    }
}

步骤:

1、通过实现IModelBinder接口,可以创建自定义模型绑定器。

2.注册自定义模型绑定器有三种方法。

方法一:在应用程序的Global.asax的Application_Sart()方法注册自定义的模型绑定器。

ModelBinders.Binders.Add(typeof(Address), new AddressModelBinder());

方法二:创建模型绑定器提供器。(这个对有多个类型进行操作的的自定义模型绑定器或有许多提供器要维护,这个是个灵活的方式)

1)通过实现IModelBinderProvider接口来创建一个模型绑定器提供器。这个接口的定义如下:

namespace System.Web.Mvc
{
    public interface IModelBinderProvider
    {
        IModelBinder GetBinder(Type modelType);
    }
}

2)这个自定义的模型绑定器提供器也需要到应用程序中注册。当然也是在Global.asax的Application_Start方法中注册。

  假如我有这么个自定义模型绑定器提供器:

  public class CustomModelBinderProvider:IModelBinderProvider
    {

        public IModelBinder GetBinder(Type modelType)
        {
            return modelType == typeof(Address) ? new AddressModerBrinder() : null;
        }
    }

那么我要注册CustomeModelBinderProvider 模型绑定器提供器,就应该这样:

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

            ModelBinderProviders.BinderProviders.Add(new CustomModelBinderProvider());

            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

方法三:使用ModelBinder注解属性指定自定义模型绑定器。

把ModelBinder注解属性应用到模型类上,指定此模型类的模型绑定器。

    [ModelBinder(typeof(AddressModelBinder))]
    public class Address
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string City{ get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
    }

自定义模型绑定系统

时间: 2024-07-29 19:58:33

自定义模型绑定系统的相关文章

原来自定义模型绑定器还可以这么玩

我有个功能,需要绑定List<User>.我做了个测试:试图: @using (Html.BeginForm("save", "user")) { <div> 用户名:<input type="text" name="UserName" /><br /> 用户名:<input type="text" name="UserName" /

ASP.NET MVC 的自定义模型绑定

最近在研究 ASP.NET MVC 模型绑定,发现 DefaultModelBinder 有一个弊端,就是无法实现对浏览器请求参数的自定义,最初的想法是想为实体模型的属性设置特性(Attribute),然后通过取得设置的特性值对属性进行赋值,研究了好久 MVC 源码之后发现可以通过重写 DefaultModelBinder 的 BindProperty 方法可以达到预期的目的. ASP.NET MVC 中有一个自定义模型绑定特性 CustomModelBinderAttribute,打算通过重写

MVC重写DefaultModelBinder实现自定义模型绑定

在编写前台页面的时候为了使url传递参数的简短,比如personId="1"  我们通过url传递成pid=1  那么在后台action方法接受的模型Person类 的属性为personid 则mvc就不能把值填充到实体类里面 所以我们要重写mvc底层填充模型的类  ,自定义一个类 继承DefaultModelBinder  重写BindProperty 方法 方法内部实现见下图 做完上面 还要在全局配置文件中配置.将我们mvc填充模型的类 替换成我们写的类 如下图: 防止以后看不懂啦

ASP.NET MVC——模型绑定

这篇文章我们来讲讲模型绑定(Model Binding),其实在初步了解ASP.NET MVC之后,大家可能都会产生一个疑问,为什么URL片段最后会转换为例如int型或者其他类型的参数呢?这里就不得不说模型绑定了.模型绑定是指,用浏览器以HTTP请求方式发送的数据来创建.NET对象的过程.每当定义具有参数的动作方法时,一直是在依赖着这种模型绑定过程. 准备项目 我们先来创建一个MVC项目,名叫MVCModels,并在Models文件夹中创建一个新的类文件Person. 1 using Syste

第22章 模型绑定

模型绑定(Model Binding)是指用浏览器以HTTP请求方式发送的数据来创建.NET对象的过程. 动作方法的参数依赖于模型绑定过程(通过模型绑定器来实现).利用整个HTTP请求所携带的数据(用户在表单中输入的数据.路由数据.请求URL中的查询字符串.请求中上传的文件)构造动作方法所需要参数对象的过程. 模型绑定过程(模型绑定器要做的事): 1.检测确认目标对象(要创建的对象,指动作方法的参数)的名称和类型:(动作方法参数的名称和类型) 2.通过对象名称查找数据源(请求),并找到可用数据(

《ASP.NET MVC 4 实战》学习笔记 11:模型绑定器与值提供器

一.创建自定义模型绑定器: 利用请求数据塑造模型对象并将对象传递给动作参数的过程称为模型绑定(Model Binding). 大多数时候动作参数是对象的主键或其他唯一标识符,因此我们可以不必在所有的动作中都放置一段重复的数据访问代码(下面代码“\\Before”部分),而是使用一个自定义的模型绑定器(下面代码“\\After”部分).它能够在动作执行之前加载存储对象,于是动作不再以唯一标识符而是以持久化的对象类型作为参数. // Before public ViewResult Edit (Gu

Kendo UI Grid 模型绑定

开篇 接触 Asp.net MVC 时间较长的童鞋可能都会了解过模型绑定(Model Binding),而且在一些做 Web 项目的公司或是Team面试中也经常会被问到.项目中有很多 Action 中都使用了自定义的模型绑定,但是业务逻辑太过复杂不适合做为例子与大家分享,而今天在做一个 Kendo UI 的功能时觉得可以用 Kendo UI 做为例子与大家分享与探讨一个典型的 Model Binding 的过程. 写的比较随性,欢迎大家讨论及拍砖! 背景介绍 Kendo UI: 它是一个非常出名

ASP.NET MVC 4 (九) 模型绑定

模型绑定指的是MVC从浏览器发送的HTTP请求中为我们创建.NET对象,在HTTP请求和C#间起着桥梁的作用.模型绑定的一个最简单的例子是带参数的控制器action方法,比如我们注册这样的路径映射: routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Inde

模型绑定时对客户端传过来的数据做处理的几种方式

有时我们从客户端获取来的数据.不一定就是我们先要的,需要做一些处理 .这里我们以一个model的属性需要做处理为例子. 这里说5种解决方法. model: public class MyModel { public string Encrypt { get; set; } public string Lala { get; set; } } Controller: public class HomeController : Controller { public void Test(MyMode