我知道 ASP.NET MVC Html 辅助扩展方法中有一个 ListBoxFor
扩展方法,但我一直认为复选框列表比列表框更用户友好。
在老式的 WebForms 中有一个非常方便的 CheckBoxList
控件,但显然现在已经不可用了。
问题是,为什么在 ASP.NET MVC 中没有办法创建复选框列表?如何编写自己的扩展方法来创建复选框列表并以与 ListBoxFor
类似的方式运行?
最佳答案
这是 CheckBoxListFor 的强类型 HtmlHelper,它在 View 数据模型中将所选项目作为数组进行处理。我选择不包装 Html.CheckBox 或 Html.CheckBoxFor 方法,因为我不希望在复选框列表中隐藏“false”字段。
请随时改进并重新发布:-)
//View
<%: Html.CheckBoxListFor(model => model.FreightTypeIds, FreightTypeMultiSelectList) %>
//Controller
public ActionResult SomeAction(int[] FreightTypeIds)
{
//...
return View();
}
//Extension
public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IEnumerable<TProperty>>> expression, MultiSelectList allOptions, object htmlAttributes = null)
{
ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression<TModel, IEnumerable<TProperty>>(expression, htmlHelper.ViewData);
// Derive property name for checkbox name
string propertyName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(modelMetadata.PropertyName);
// Get currently select values from the ViewData model
IEnumerable<TProperty> list = expression.Compile().Invoke(htmlHelper.ViewData.Model);
// Convert selected value list to a List<string> for easy manipulation
IList<string> selectedValues = new List<string>();
if (list != null)
{
selectedValues = new List<TProperty>(list).ConvertAll<string>(delegate(TProperty i) { return i.ToString(); });
}
// Create div
TagBuilder divTag = new TagBuilder("div");
divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
// Add checkboxes
foreach (SelectListItem item in allOptions)
{
divTag.InnerHtml += string.Format(
"<div><input type=\"checkbox\" name=\"{0}\" id=\"{1}_{2}\" " +
"value=\"{2}\" {3} /><label for=\"{1}_{2}\">{4}</label></div>",
propertyName,
TagBuilder.CreateSanitizedId(propertyName),
item.Value,
selectedValues.Contains(item.Value) ? "checked=\"checked\"" : string.Empty,
item.Text);
}
return MvcHtmlString.Create(divTag.ToString());
}
关于.net - 如何在 ASP.NET MVC 中创建 CheckBoxListFor 扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3889397/