[ASP.NET MVC]为HtmlHelper添加一个RadioButtonList扩展方法
发布时间:2020-12-16 09:09:32 所属栏目:asp.Net 来源:网络整理
导读:在前面一篇文章中,我们通过对HtmlHelper的扩展简化了对DropDownList(Single-Line-Select)和ListBox(Multiple-Line-Select)的绑定,以及对作为数据源的列表进行单独维护。现在我们为HtmlHelper/HtmlHelperModel添加一个RadioButtonList/RadioButtonListF
在前面一篇文章中,我们通过对HtmlHelper的扩展简化了对DropDownList(Single-Line-Select)和ListBox(Multiple-Line-Select)的绑定,以及对作为数据源的列表进行单独维护。现在我们为HtmlHelper/HtmlHelper<Model>添加一个RadioButtonList/RadioButtonListFor扩展方法实现一组RadioButton的绑定。[源代码从这里下载] 一、RadioButtonListFor的使用我们先来显示一下扩展的RadioButtonListFor的方法的用法。如下所示的是作为Model的Person类型,其Gender(Male/Female)、MaritalStatus(Single/Married)和Country的选项列表通过独立的组件CodeManager进行单独维护。 1: public class Person 3: string Name { get; set; }
5: [Display(Name = "Marital Status")]
7: string Country { get; set; }
2: @model Person4: ViewBag.Title = "Index";6: @using (Html.BeginForm())8: <table id="container">10: td class="label">@Html.LabelFor(m => m.Name):</td 11: >@Html.EditorFor(m => m.Name) 12: 13: 14: > m.Gender): 15: >@Html.RadioButtonListFor(m => m.Gender,"Gender") 16: 17: 18: > m.MaritalStatus): 19: > m.MaritalStatus,"MaritalStatus") 20: 21: 22: > m.Country): 23: > m.Country,"Country",RepeatDirection.Vertical) 24: >28: table>class CodeDescriptionstring Description { get; set; }6:?8: { 三、RadioButtonList/RadioButtonListFor扩展方法如下所示的是RadioButtonList/RadioButtonListFor两个扩展方法的定义,参数codeCategory表示作为数据源的列表类别,而RepeatDirection 枚举类型则代表同组的RadioButton的排列方向,默认为水平。从上面的例子我们可以看到,我们通过这个参数将名称为Country的RadioButtonList进行了纵向排列。通过Html生成代码我们可以看出,我们采用了Table作为布局方式,实际上ASP.NET的RadioButtonList也是这么做的。 static MvcHtmlString RadioButtonList(this HtmlHelper htmlHelper,1)">string name,1)">string codeCategory,RepeatDirection repeatDirection = RepeatDirection.Horizontal,IDictionary<string,1)">object> htmlAttributes = null)
5: var codes = CodeManager.GetCodes(codeCategory); 7: } 9: { 11: 13: string name = ExpressionHelper.GetExpressionText(expression);
15: foreach (var item in attributes) 17: htmlAttributes.Add(item); string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); return GenerateHtml(fullHtmlFieldName,stateValue); 23: static MvcHtmlString GenerateHtml(object> htmlAttributes,1)">string stateValue = 24: { 26: int i = 0;
28: { 30: foreach (var code in codes) 32: i++; 34: TagBuilder td = "td");
36: tr.InnerHtml+=td.ToString(); 38: table.InnerHtml = tr.ToString(); 40: else
42: 43: {
45: i++; 47: TagBuilder td = "td");
49: tr.InnerHtml = td.ToString(); 51: } 53: return new MvcHtmlString(table.ToString()); 55:? 57: { 59:? 61: label.MergeAttribute("for",id);
63:? 65: input.GenerateId(id); 67: input.MergeAttribute("type",1)">"radio");
69: input.MergeAttributes(htmlAttributes); 71: { 73: } 75: sb.AppendLine(label.ToString()); 77: } 相关内容
推荐文章
站长推荐
热点阅读
|