mvc htmlhelper 复选框扩展

public static class CheckBoxListExtend
{
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);
HashSet<string> set = new HashSet<string>();
List<SelectListItem> list = new List<SelectListItem>();

//获取选中的值
if (selectList != null)
{
SelectList selList = selectList as SelectList;
if (selList != null && selList.SelectedValue != null)
{
string selectedValues = selList.SelectedValue.ToString();
if (!string.IsNullOrEmpty(selectedValues))
{
if (selectedValues.Contains(","))
{
string[] tempStr = selectedValues.Split(‘,‘);
for (int i = 0; i < tempStr.Length; i++)
{
set.Add(tempStr[i]);
}
}
else
{
set.Add(selectedValues);
}
}
}
foreach (SelectListItem item in selectList)
{
item.Selected = (item.Value != null) ? set.Contains(item.Value) : set.Contains(item.Text);
list.Add(item);
}
}

selectList = list;
HtmlAttributes.Add("type", "checkbox");
//HtmlAttributes.Add("_name", l);
HtmlAttributes.Add("name", name);

StringBuilder stringBuilder = new StringBuilder();
foreach (SelectListItem selectItem in selectList)
{
IDictionary<string, object> newHtmlAttributes = HtmlAttributes.DeepCopy();
newHtmlAttributes.Add("value", selectItem.Value);
newHtmlAttributes.Add("txt", selectItem.Text);
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(@" {0} {1}", 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;
}
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。