您的位置:首页 > 编程语言 > ASP

ASP .NET MVC HtmlHelper扩展——简化“列表控件”的绑定

2015-01-30 12:46 267 查看
在众多表单元素中,有一类<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的列表项。

public class CodeDescription
{
 public string Id{ get; set;}
 public string Code{ get; set;}
 public string Description{ get; set;}
public string Category{get;set;}
 public DateTime EffectiveStartDate{ get; set;}
 public DateTime EffectiveEndDate{ get; set;}
 public CodeDescription(string code, string description, string category)
{
 this.Id = Guid.NewGuid().ToString();
 this.Code = code;
 this.Description = description;
 this.Category = category;
 this.EffectiveStartDate = DateTime.MinValue;
 this.EffectiveEndDate = DateTime.MaxValue;
}
}
如下所示的CodeCollection 表示一组CodeDescription列表,它直接继承自Collection<CodeDescription>类型。由于CodeDescription具有有效期限的概念,我们需要筛选出当前有效的Code,所以我们定义了如下一个GetEffectiveCodes方法。

public class CodeCollection : Collection<CodeDescription>
{
 public IEnumerable<CodeDescription> GetEffectiveCodes()
{
 return this.Where(code => code.EffectiveStartDate <= DateTime.Today && code.EffectiveEndDate >= DateTime.Today).ToList();
}
}
在进行Code绑定的时候,我们都是“类别”为单位的。我们总是获取某一个类别(比如国家、性别、婚姻状况和政治面貌等)的Code列表绑定到界面上。如下所示的CodeManager定义了一个GetCode方法获取指定类别的Code列表。而作为Code存储,我们采用了静态字段的形式,从如下所示的代码可以看出我们实际定义了三类Code,即Gender、MaritalStatus和Country,分别表示性别、婚姻状况和国籍。

public static class CodeManager
{
 private static CodeDescription[] codes = new CodeDescription[]
{
 new CodeDescription("M","Male","Gender"),
 new CodeDescription("F","Female","Gender"),
 new CodeDescription("S","Single","MaritalStatus"),
 new CodeDescription("M","Married","MaritalStatus"),
 new CodeDescription("CN","China","Country"),
 new CodeDescription("US","Unite States","Country"),
 new CodeDescription("UK","Britain","Country"),
 new CodeDescription("SG","Singapore","Country")
};
 public static CodeCollection GetCodes(string category)
{
 CodeCollection codeCollection = new CodeCollection();
 foreach(var code in codes.Where(code=>code.Category == category))
{
 codeCollection.Add(code);
}
 return codeCollection;
}
}

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

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

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

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

public static class SelectExtensions
{
 public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, string codeCategory, BindingOption bindingOption = null)
{
 bindingOption = bindingOption ?? new BindingOption();
 var listItems = GenerateListItems(codeCategory, bindingOption);
 return htmlHelper.DropDownList(name, listItems, bindingOption.OptionalLabel);
} 
 public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string codeCategory, BindingOption bindingOption = null)
{
 bindingOption = bindingOption ?? new BindingOption();
 var listItems = GenerateListItems(codeCategory, bindingOption);
 return htmlHelper.DropDownListFor<TModel, TProperty>(expression, listItems,bindingOption.OptionalLabel);
}
 public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name, string codeCategory, BindingOption bindingOption = null)
{
 bindingOption = bindingOption ?? new BindingOption();
 var listItems = GenerateListItems(codeCategory, bindingOption);
 return htmlHelper.ListBox(name, listItems, bindingOption.OptionalLabel);
}
 public static MvcHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string codeCategory, BindingOption bindingOption = null)
{
 bindingOption = bindingOption ?? new BindingOption();
 var listItems = GenerateListItems(codeCategory, bindingOption);
 return htmlHelper.ListBoxFor<TModel, TProperty>(expression, listItems);
}
 public static IEnumerable<SelectListItem> GenerateListItems(string codeCategory, BindingOption bindingOption)
{
 var items = new List<SelectListItem>();
 foreach (var code in CodeManager.GetCodes(codeCategory).GetEffectiveCodes())
{
 var item = new SelectListItem
{
 Text = FormatTemplate(bindingOption.TextTemplate, code),
 Value = FormatTemplate(bindingOption.ValueTemplate, code)
};
 items.Add(item);
}
 return items;
}
 private static string FormatTemplate(string template, CodeDescription code)
{
 return template.Replace("{Id}", code.Id)
 .Replace("{Code}", code.Code)
 .Replace("{Description}", code.Description);
}
}

三、使用这些扩展方法

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

public class Person
{
 public string Name{ get; set;}
 public string Gender{ get; set;}
 [Display(Name = "MaritalStatus")]
 public string MaritalStatus{ get; set;}
 public string Country{ get; set;}
}
public class HomeController : Controller
{
 public ActionResult Index()
{
 return View(new Person
{
 Name = "Zhan San",
 Gender = "M",
 Country = "CN",
 MaritalStatus = "S"
});
}
}
我们定义的扩展方法是用在Index操作定义的Index.cshtml视图中,下面是Index.cshtml的定义:

@model CodeBinding.Models.Person
@{
 ViewBag.Title = "Index";
}
<table>
 <tr>
 <td>@Html.LabelFor(m=>m.Name)</td>
 <td>@Html.TextBoxFor(m=>m.Name)</td>
 </tr>
 <tr>
 <td>@Html.LabelFor(m=>m.Gender)</td>
 <td>@Html.DropDownListFor(m => m.Gender, "Gender", new BindingOption
{
OptionalLabel = "Please select your gender...",
TextTemplate = "{Code}-{Description}",
ValueTemplate = "{Code}"
})</td>
 </tr>
<tr>
 <td>@Html.LabelFor(m=>m.MaritalStatus)</td>
 <td>@Html.DropDownListFor(m => m.MaritalStatus, "MaritalStatus",new BindingOption
{
OptionalLabel = "Please select your marital status...",
TextTemplate = "{Code}-{Description}",
ValueTemplate = "{Code}"
})</td>
 </tr>
<tr>
 <td>@Html.LabelFor(m=>m.Country)</td>
 <td>@Html.ListBoxFor(m => m.Country, "Country")</td>
 </tr>
</table>
最后看看最终呈现出来的效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: