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;
}
}