HtmlHelper拓展实现CheckBoxList

时间:2022-04-26 09:00:34

经过一番折腾(主要是SelectList这个类操作有些繁琐)实现了CheckBoxList,过程RadioList基本一样

拓展方法

    public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList)
    {
        return CheckBoxList(htmlHelper, name, selectList, null, null, null, 1);
    }
    public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, int col)
    {
        return CheckBoxList(htmlHelper, name, selectList, null, null, null, col);
    }
    public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string rowClass, string CheckBoxClass, string spanClass, int col)
    {
        return CheckBoxListHelper(htmlHelper, metadata: null, name: name, selectList: selectList, rowClass: rowClass, checkBoxClass: CheckBoxClass, spanClass: spanClass, col: col);
    }
    public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
    {
        return CheckBoxListFor(htmlHelper, expression, selectList, null, null, null, 1);
    }
    public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, int col)
    {
        return CheckBoxListFor(htmlHelper, expression, selectList, null, null, null, col);
    }
    public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string rowClass, string CheckBoxClass, string spanClass, int col)
    {
        if (expression == null)
        {
            throw new ArgumentNullException("expression");
        }
        //可以不用
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        return CheckBoxListHelper(htmlHelper, metadata, ExpressionHelper.GetExpressionText(expression), selectList, rowClass, CheckBoxClass, spanClass, col);
    }
    public static MvcHtmlString CheckBoxListHelper(this HtmlHelper htmlHelper, ModelMetadata metadata, string name, IEnumerable<SelectListItem> selectList, string rowClass, string checkBoxClass, string spanClass, int col)
    {
        StringBuilder resultString = new StringBuilder();
        if (checkBoxClass == null) checkBoxClass = "";
        if (rowClass == null) rowClass = "";
        if (spanClass == null) spanClass = "";
        StringBuilder checkBox = new StringBuilder("<input type=\"checkBox\" class=\"" + checkBoxClass + "\" name=\"" + name + "\" value=\"noValue\" isChecked /><span class=\"" + spanClass + "\">noText</span>");
        StringBuilder tempcheckBox = new StringBuilder();
        StringBuilder tempLine = new StringBuilder();
        var selectValues = (IEnumerable<string>)((SelectList)selectList).SelectedValue;

        int tempCol = col;
        foreach (SelectListItem selectItem in selectList)
        {
            tempcheckBox = new StringBuilder(checkBox.ToString());
            if (selectValues.Contains(selectItem.Value))
            {
                tempcheckBox.Replace("isChecked", "checked");
            }
            else
            {
                tempcheckBox.Replace("isChecked", "");
            }
            tempcheckBox.Replace("noValue", selectItem.Value);
            tempcheckBox.Replace("noText", selectItem.Text);
            tempLine.Append(tempcheckBox);
            if (--tempCol == 0)
            {//要换行
                tempLine.WearDiv(rowClass);
                resultString.Append(tempLine);
                tempCol = col;
                tempLine.Clear();
            }
        }
        if (tempLine.Length != 0)
        {
            tempLine.WearDiv("");
        }
        resultString.Append(tempLine);
        return new MvcHtmlString(resultString.ToString());
    }

 HttpGet

      public ActionResult EditPerson(string id)
        {
            IService service = new Service();
            var person = service.GetPersons().FirstOrDefault(lbItem => lbItem.Id == id);
            if (person == null)
                throw new NullReferenceException();
            //性别列表
            var sexList = new List<object>();
            sexList.Add(new { Value = "nan", Text = "男" });
            sexList.Add(new { Value = "nv", Text = "女" });
            var sexSelectList = new SelectList(sexList, "Value", "Text",person.Sex);
            //学位列表
            var dipList = new List<object>();
            dipList.Add(new { Value = "dz", Text = "大专" });
            dipList.Add(new { Value = "bs", Text = "博士" });
            dipList.Add(new { Value = "yjs", Text = "研究生" });
            dipList.Add(new { Value = "gz", Text = "高中" });
            var dipSelectList = new SelectList(dipList, "Value", "Text",person.Diploma);
            //爱好列表
            var personHobbies = person.Hobbies.ToList();
            var allHobbies = service.GetHobbies().ToList();
            var hobbySelectList = new SelectList(allHobbies, "Id", "Name", personHobbies.Select(a => a.Id).ToList());


            ViewData["RadioSexList"] = sexSelectList;
            ViewData["RadioDiplomaList"] = dipSelectList;
            ViewData["CheckBoxHobbyList"] = hobbySelectList;
            return View(person);
        }

 cshtml

@model MyExtend.Controllers.Person
@{
    Layout = null;
    ViewBag.Title = "EditPerson";
}

<h2>EditPerson</h2>

@using (Html.BeginForm("SaveEdit", "CheeseBar", FormMethod.Post))
{
    <div>
        @Html.EditorFor(model => model.Name)
    </div>
    <div>
        @Html.RadioListFor(model => model.Sex, (SelectList)ViewData["RadioSexList"],"rowClass","radioClass","spanClass",1)
    </div>
    <div>
        @Html.RadioList("Diploma", (SelectList)ViewData["RadioDiplomaList"],"rowClass", "radioClass", "spanClass", 2)
    </div>

    <div>
        @Html.CheckBoxListFor(model => model.Hobbies, (SelectList)ViewData["CheckBoxHobbyList"],2)
    </div>
}

 HtmlHelper拓展实现CheckBoxList

 

 

 编辑后提交,save方法添加断点

HtmlHelper拓展实现CheckBoxList