Fork me on GitHub
[ASP.NET MVC]通过对HtmlHelper扩展简化“列表控件”的绑定

在众多表单元素中,有一类<select>元素用于绑定一组预定义列表。传统的ASP.NET Web Form中,它对应着一组重要的控件类型,即ListControl,我们经常用到DropDownList, ListBox、CheckBoxList和RadioButtonList都是其子类。ASP.NET MVC通过对HtmlHelper和HtmlHelper<TModel>的扩展实现了对不同类型的<select>元素的绑定,它们以扩展方法的形式定义在SelectExtensions中。当我们在操作这些扩展方法的时候,必须手工地提供以 IEnumerable<SelectListItem>对象表示的列表项。如果我们建立一个独立的组件来维护这些预定的列表,那么我们就可以定义一些更加简单的扩展方法以避免手工地指定列表项。[源代码从这里下载]

一、创建一个独立的列表维护组件

我们将这些绑定在<select>元素中的预定义列表中的元素称为Code。作为简单的演示模拟,我们创建了一个名为CodeManager的组件。我们先来看看用于描述单一Code的CodeDescription类型的定义,如下面的代码所示,CodeDescription具有ID、Code、Description、EffectiveStartDate 和EffectiveEndDate。以表示国家的列表为例,Code代表某个国家的代码(比如CN),Description则是一个可读性的描述(比如China)。EffectiveStartDate 和EffectiveEndDate决定了Code的有效期限,比如一组表示“税率”的列表,在不同的时间范围内可能采用不同的列表。换言之,作为统一类别(通过Category属性表示)的列表中可能具有“多套”,它们可以共享相同的Code,我们通过ID来区分这些具有相同Code的列表项。

   1: public class CodeDescription
   2: {
   3:     public string Id { get; set; }
   4:     public string Code { get; set; }
   5:     public string Description { get; set; }
   6:     public string Category{get;set;}
   7:     public DateTime EffectiveStartDate { get; set; }
   8:     public DateTime EffectiveEndDate { get; set; }
   9:  
  10:     public CodeDescription(string code, string description, string category)
  11:     {
  12:         this.Id = Guid.NewGuid().ToString();
  13:         this.Code = code;
  14:         this.Description = description;
  15:         this.Category = category;
  16:         this.EffectiveStartDate = DateTime.MinValue;
  17:         this.EffectiveEndDate = DateTime.MaxValue;
  18:     }
  19: }

如下所示的CodeCollection 表示一组CodeDescription列表,它直接继承自Collection<CodeDescription>类型。由于CodeDescription具有有效期限的概念,我们需要筛选出当前有效的Code,所以我们定义了如下一个GetEffectiveCodes方法。

   1: public class CodeCollection : Collection<CodeDescription>
   2: {
   3:     public IEnumerable<CodeDescription> GetEffectiveCodes()
   4:     {
   5:         return this.Where(code => code.EffectiveStartDate <= DateTime.Today && code.EffectiveEndDate >= DateTime.Today).ToList();
   6:     }
   7: }

在进行Code绑定的时候,我们都是“类别”为单位的。我们总是获取某一个类别(比如国家、性别、婚姻状况和政治面貌等)的Code列表绑定到界面上。如下所示的CodeManager定义了一个GetCode方法获取指定类别的Code列表。而作为Code存储,我们采用了静态字段的形式,从如下所示的代码可以看出我们实际定义了三类Code,即Gender、MaritalStatus和Country,分别表示性别、婚姻状况和国籍。

   1: public static class CodeManager
   2: {
   3:     private static CodeDescription[] codes = new CodeDescription[]
   4:     {
   5:         new CodeDescription("M","Male","Gender"),
   6:         new CodeDescription("F","Female","Gender"),
   7:         new CodeDescription("S","Single","MaritalStatus"),
   8:         new CodeDescription("M","Married","MaritalStatus"),
   9:         new CodeDescription("CN","China","Country"),
  10:         new CodeDescription("US","Unite States","Country"),
  11:         new CodeDescription("UK","Britain","Country"),
  12:         new CodeDescription("SG","Singapore","Country")
  13:     };
  14:     public static CodeCollection GetCodes(string category)
  15:     {
  16:         CodeCollection codeCollection = new CodeCollection();
  17:         foreach(var code in codes.Where(code=>code.Category == category))
  18:         {
  19:             codeCollection.Add(code);
  20:         }
  21:         return codeCollection;
  22:     }
  23: }

 

二、定义HtmlHelper的扩展方法实现基于“列表类别”的绑定

现在我们来定义针对HtmlHelper的扩展方法通过从CodeManager获取的Code列表来进行“列表控件”的绑定。表示列表项的SelectListItem具有Text和Value两个属性,分别表示显示的文本和对应的值。在默认的情况下,它们应该对应于CodeDescription的Description和Code,但是有时候却需要进行相应的定制。比如说,有时候我们希望通过CodeDescription的ID来作为SelectListItem的值,或者说通过将SelectListItem显示为Code和Description的组合,比如“CN-China”。为此我们定义了如下一个BindingOption类型。

   1: public class BindingOption
   2: {
   3:     public string OptionalLabel { get;  set; }
   4:     public string TextTemplate { get; set; }
   5:     public string ValueTemplate { get; set; }
   6:  
   7:     public BindingOption()
   8:     {
   9:         this.OptionalLabel = null;
  10:         this.TextTemplate = "{Description}";
  11:         this.ValueTemplate = "{Code}";
  12:     }
  13: }

OptionalLabel表示添加的提示性的文本(比如“请选择一个Xxx”),而TextTemplate 和ValueTemplate 表示最终作为SelectListItem的Text和Value属性的模板,模板中包含相应的站位符({Id}、{Code}和{Description})。

我们为HtmlHelper编写了如下4个扩展方法用于针对DropDownList和ListBox的绑定,在参数中我们无须提供SelectListItem列表,而只需要提供Code和类别即可。而BindingOption 决定了最终作为SelectListItem的Text和Value属性,以及是否需要添加一个提示性的文字和文字内容。在真正的项目中,我们可以将BindingOption的设置定义在配置文件中。

   1: public static class SelectExtensions
   2: {
   3:     public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, string codeCategory, BindingOption bindingOption = null)
   4:     {
   5:         bindingOption = bindingOption ?? new BindingOption();
   6:         var listItems = GenerateListItems(codeCategory, bindingOption);
   7:         return htmlHelper.DropDownList(name, listItems, bindingOption.OptionalLabel);
   8:     }   
   9:     public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string codeCategory, BindingOption bindingOption = null)
  10:     {
  11:         bindingOption = bindingOption ?? new BindingOption();
  12:         var listItems = GenerateListItems(codeCategory, bindingOption);
  13:         return htmlHelper.DropDownListFor<TModel, TProperty>(expression, listItems,bindingOption.OptionalLabel);
  14:     }
  15:  
  16:     public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name, string codeCategory, BindingOption bindingOption = null)
  17:     {
  18:         bindingOption = bindingOption ?? new BindingOption();
  19:         var listItems = GenerateListItems(codeCategory, bindingOption);
  20:         return htmlHelper.ListBox(name, listItems, bindingOption.OptionalLabel);
  21:     }
  22:     public static MvcHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string codeCategory, BindingOption bindingOption = null)
  23:     {
  24:         bindingOption = bindingOption ?? new BindingOption();
  25:         var listItems = GenerateListItems(codeCategory, bindingOption);
  26:         return htmlHelper.ListBoxFor<TModel, TProperty>(expression, listItems);
  27:     }
  28:  
  29:     public static IEnumerable<SelectListItem> GenerateListItems(string codeCategory, BindingOption bindingOption)
  30:     {
  31:         var items = new List<SelectListItem>();
  32:         foreach (var code in CodeManager.GetCodes(codeCategory).GetEffectiveCodes())
  33:         {
  34:             var item = new SelectListItem
  35:             {
  36:                 Text = FormatTemplate(bindingOption.TextTemplate, code),
  37:                 Value = FormatTemplate(bindingOption.ValueTemplate, code)
  38:             };
  39:             items.Add(item);
  40:         }
  41:         return items;
  42:     }
  43:  
  44:     private static string FormatTemplate(string template, CodeDescription code)
  45:     {
  46:         return template.Replace("{Id}", code.Id)
  47:             .Replace("{Code}", code.Code)
  48:             .Replace("{Description}", code.Description);
  49:     }
  50: }

 

三、使用这些扩展方法

现在我们创建一个简单的ASP.NET MVC应用来演示对DropDownList和ListBox的绑定。为此我们定义了如下一个Person类型,其Gender、MaritalStatus 和Country 属性分别对应于CodeManager维护的三组Code。在创建的HomeController中,我们将初始化Person对象的呈现定义在Index操作中。

   1: public class Person
   2: {
   3:     public string Name { get; set; }
   4:     public string Gender { get; set; }
   5:     [Display(Name = "MaritalStatus")]
   6:     public string MaritalStatus { get; set; }
   7:     public string Country { get; set; }
   8: }
   9:  
  10: public class HomeController : Controller
  11: {
  12:     public ActionResult Index()
  13:     {
  14:         return View(new Person
  15:         {
  16:             Name = "Zhan San",
  17:             Gender = "M",
  18:             Country = "CN",
  19:             MaritalStatus = "S"
  20:         });
  21:     }
  22: }

我们定义的扩展方法是用在Index操作定义的Index.cshtml视图中,下面是Index.cshtml的定义:

   1: @model CodeBinding.Models.Person
   2: @{
   3:     ViewBag.Title = "Index";
   4: }
   5:  
   6: <table>
   7:     <tr>
   8:         <td>@Html.LabelFor(m=>m.Name)</td>
   9:         <td>@Html.TextBoxFor(m=>m.Name)</td>
  10:     </tr>
  11:     <tr>
  12:         <td>@Html.LabelFor(m=>m.Gender)</td>
  13:         <td>@Html.DropDownListFor(m => m.Gender, "Gender", new BindingOption
  14:        {
  15:            OptionalLabel = "Please select your gender...",
  16:            TextTemplate = "{Code}-{Description}",
  17:            ValueTemplate = "{Code}"
  18:        })</td>
  19:     </tr>
  20:      <tr>
  21:         <td>@Html.LabelFor(m=>m.MaritalStatus)</td>
  22:         <td>@Html.DropDownListFor(m => m.MaritalStatus, "MaritalStatus",new BindingOption
  23:        {
  24:            OptionalLabel = "Please select your marital status...",
  25:            TextTemplate = "{Code}-{Description}",
  26:            ValueTemplate = "{Code}"
  27:        })</td>
  28:     </tr>
  29:      <tr>
  30:         <td>@Html.LabelFor(m=>m.Country)</td>
  31:         <td>@Html.ListBoxFor(m => m.Country, "Country")</td>
  32:     </tr>
  33: </table>

最后看看最终呈现出来的效果:

image

作为Controller基类ControllerBase的Execute方法的核心在于对Action方法的执行和作为方法返回的ActionResult的执行,两者的执行是通过一个叫做ActionInvoker的组件来完成的。

一、ActionInvoker

我们同样为ActionInvoker定义了一个接口IActionInvoker。如下面的代码片断所示,该接口定义了一个唯一的方法InvokeAction用于执行指定名称的Action方法,该方法的第一个参数是一个表示基于当前Controller上下文的ControllerContext对象。

   1: public interface IActionInvoker
   2: {
   3:     void InvokeAction(ControllerContext controllerContext, string actionName);
   4: }

ControllerContext类型在真正的ASP.NET MVC框架中要负责一些,在这里我们对它进行了简化,仅仅将它表示成对当前Controller和请求上下文的封装,而这两个要素分别通过如下所示的Controller和RequestContext属性表示。

   1: public class ControllerContext
   2: {
   3:     public ControllerBase Controller { get; set; }
   4:     public RequestContext RequestContext { get; set; }
   5: }

ControllerBase中表示ActionInvoker的同名属性在构造函数中被初始化。在Execute方法中,通过作为方法参数的RequestContext对象创建ControllerContext对象,并通过包含在RequestContext中的RouteData得到目标Action的名称,然后将这两者作为参数调用ActionInvoker的InvokeAction方法。

从前面给出的关于ControllerBase的定义我们可以看到在构造函数中默认创建的ActionInvoker是一个类型为ControllerActionInvoker的对象。如下所示的代码片断反映了整个ControllerActionInvoker的定义,而InvokeAction方法的目的在于实现针对Action方法的执行。由于Action方法具有相应的参数,在执行Action方法之前必须进行参数的绑定。ASP.NET MVC将这个机制成为Model的绑定,而这又涉及到另一个重要的组件ModelBinder。

   1: public class ControllerActionInvoker: IActionInvoker
   2: {
   3:     public IModelBinder ModelBinder { get; private set; }
   4:     public ControllerActionInvoker()
   5:     {
   6:         this.ModelBinder = new DefaultModelBinder();
   7:     }
   8:     public void InvokeAction(ControllerContext controllerContext, string actionName)
   9:     {
  10:         MethodInfo method = controllerContext.Controller.GetType().GetMethod(actionName);
  11:         List<object> parameters = new List<object>();
  12:         foreach (ParameterInfo parameter in method.GetParameters())
  13:         { 
  14:                 parameters.Add(this.ModelBinder.BindModel(controllerContext,parameter.Name,parameter.ParameterType));
  15:         }
  16:         ActionResult actionResult = method.Invoke(controllerContext.Controller,parameters.ToArray()) as ActionResult;
  17:         actionResult.ExecuteResult(controllerContext);
  18:     }
  19: }

二、ModelBinder

我们为ModelBinder提供了一个如下一个简单的定义,这与在真正的ASP.NET MVC中的同名接口的定义不尽相同。该接口具有唯一的BindModel根据ControllerContext和Model名称(在这里实际上是参数名称)和类型得到一个作为参数的对象。

   1: public interface IModelBinder
   2: {
   3: object BindModel(ControllerContext controllerContext, string modelName, Type modelType);
   4: }

通过前面给出的关于ControllerActionInvoker的定义我们可以看到在构造函数中默认创建的ModelBinder对象是一个DefaultModelBinder对象。由于仅仅是对ASP.NET MVC的模拟,定义在自定义的DefaultModelBinder中的Model绑定逻辑比ASP.NET MVC中同名类型中实现的要简单得多。

如下面的代码片断所示,绑定到参数上的数据具有三个来源:HTTP-POST Form、RouteData和Values和DataTokens,它们都是字典结构的数据集合。如果参数类型为字符串或者简单的值类型,我们直接根据参数名称和Key进行匹配;对于复杂类型(比如之前例子中定义的包含Contrller和Action名称的数据类型SimpleModel),则通过反射根据类型创建新的对象并根据属性名称与Key的匹配关系对相应的属性进行赋值。

   1: public class DefaultModelBinder : IModelBinder
   2: {
   3:     public object BindModel(ControllerContext controllerContext, string modelName, Type modelType)
   4:     {
   5:         if (modelType.IsValueType || typeof(string) == modelType)
   6:         {
   7:             object instance;
   8:             if (GetValueTypeInstance(controllerContext, modelName, modelType, out instance))
   9:             {
  10:                 return instance;
  11:             };
  12:             return Activator.CreateInstance(modelType);
  13:         }
  14:         object modelInstance = Activator.CreateInstance(modelType);
  15:         foreach (PropertyInfo property in modelType.GetProperties())
  16:         {
  17:             if (!property.CanWrite || (!property.PropertyType.IsValueType && property.PropertyType!= typeof(string)))
  18:             {
  19:                 continue;
  20:             }
  21:             object propertyValue;
  22:             if (GetValueTypeInstance(controllerContext, property.Name, property.PropertyType, out propertyValue))
  23:             {
  24:                 property.SetValue(modelInstance, propertyValue, null);
  25:             }
  26:         }
  27:         return modelInstance;
  28:     }
  29:     private  bool GetValueTypeInstance(ControllerContext controllerContext, string modelName, Type modelType, out object value)
  30:     {
  31:         var form = HttpContext.Current.Request.Form;
  32:         string key;
  33:         if (null != form)
  34:         {
  35:             key = form.AllKeys.FirstOrDefault(k => string.Compare(k, modelName, true) == 0);
  36:             if (key != null)
  37:             {
  38:                 value =  Convert.ChangeType(form[key], modelType);
  39:                 return true;
  40:             }
  41:         }
  42:  
  43:         key = controllerContext.RequestContext.RouteData.Values
  44:             .Where(item => string.Compare(item.Key, modelName, true) == 0)
  45:             .Select(item => item.Key).FirstOrDefault();
  46:         if (null != key)
  47:         {
  48:             value = Convert.ChangeType(controllerContext.RequestContext.RouteData.Values[key], modelType);
  49:             return true;
  50:         }
  51:  
  52:         key = controllerContext.RequestContext.RouteData.DataTokens
  53:             .Where(item => string.Compare(item.Key, modelName, true) == 0)
  54:             .Select(item => item.Key).FirstOrDefault();
  55:         if (null != key)
  56:         {
  57:             value = Convert.ChangeType(controllerContext.RequestContext.RouteData.DataTokens[key], modelType);
  58:             return true;
  59:         }
  60:         value = null;
  61:         return false;
  62:     }
  63: }

在ControllerActionInvoker的InvokeAction方法中,我们直接将传入的Action名称作为方法名从Controller类型中得到表示Action操作的MethodInfo对象。然后遍历MethodInfo的参数列表,对于每一个ParameterInfo对象,我们将它的Name和ParameterType属性表示的参数名称和类型连同创建ControllerContext作为参数调用ModelBinder的BindModel方法并得到对应的参数值。最后通过反射的方式传入参数列表并执行MethodInfo。和真正的ASP.NET MVC一样,定义在Contrller的Action方法返回一个ActionResult对象,我们通过指定它的Execute方法是先对请求的响应。

三、ActionResult

我们为具体的ActionResult定义了一个ActionResult抽象基类。如下面的代码片断所示,该抽象类具有一个参数类型为ControllerContext的抽象方法ExecuteResult,我们最终对请求的响应就实现在这里。

   1: public abstract class ActionResult
   2: {        
   3:     public abstract void ExecuteResult(ControllerContext context);
   4: }

在之前创建的例子中,Action方法返回的是一个类型为RawContentResult的对象。顾名思义,RawContentResult将初始化时指定的内容(字符串)原封不动地写入针对当前请求的HTTP回复中,具体的实现如下所示。

   1: public class RawContentResult: ActionResult
   2: {
   3:     public string RawData { get; private set; }
   4:     public RawContentResult(string rawData)
   5:     {
   6:         RawData = rawData; 
   7:     }
   8:     public override void ExecuteResult(ControllerContext context)
   9:     {
  10:         context.RequestContext.HttpContext.Response.Write(this.RawData);
  11:     }
  12: }

ASP.NET MVC是如何运行的[1]: 建立在“伪”MVC框架上的Web应用 
ASP.NET MVC是如何运行的[2]: URL路由 
ASP.NET MVC是如何运行的[3]: Controller的激活 
ASP.NET MVC是如何运行的[4]: Action的执行

作者:Artech
出处:http://artech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
posted on 2012-03-13 22:58  HackerVirus  阅读(227)  评论(0编辑  收藏  举报