mvc3 CheckBoxList扩展
mvc3 CheckBoxList扩展,mvc3的模板也有很多html扩展,但是好像实现了部分重点的,有时候还需要这样去扩展,其实这样是对的,总得给程序员留点空间吧。代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Web.Mvc; namespace Syw.Framework.Mvc { public static class CheckBoxListExtensions { public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList) { return CheckBoxList(helper, name, selectList, new { }); } public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes) { IDictionary<string, object> HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); HtmlAttributes.Add("type", "checkbox"); HtmlAttributes.Add("id", name); HtmlAttributes.Add("name", name); //HtmlAttributes.Add("style", "margin:0 0 0 10px;line-height:30px; vertical-align:-8px;border:none;"); StringBuilder stringBuilder = new StringBuilder(); foreach (SelectListItem selectItem in selectList) { IDictionary<string, object> newHtmlAttributes = HtmlAttributes.DeepCopy(); newHtmlAttributes.Add("value", selectItem.Value); if (selectItem.Selected) { newHtmlAttributes.Add("checked", "checked"); } TagBuilder tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes<string, object>(newHtmlAttributes); string inputAllHtml = tagBuilder.ToString(TagRenderMode.SelfClosing); stringBuilder.AppendFormat(@"<label style=""margin:0 0 0 10px;""> {0} {1}</label>", inputAllHtml, selectItem.Text); } return MvcHtmlString.Create(stringBuilder.ToString()); } private static IDictionary<string, object> DeepCopy(this IDictionary<string, object> ht) { Dictionary<string, object> _ht = new Dictionary<string, object>(); foreach (var p in ht) { _ht.Add(p.Key, p.Value); } return _ht; } } }
调用的时候需要在模板上引用@using Syw.Framework.Mvc;
这样就可以直接@Html.CheckBoxList("ItemType", Model.ItemList)这样调用扩展了
(0)条评论 订阅