MVC Enum RadioButtonList 助手





5.00/5 (3投票s)
用于从枚举生成单选按钮列表的 MVC Razor 助手。
引言
我遇到一个问题,我想使用 Radio Button List 来选择枚举值。我在网上找到了 Jon Lanceley 的一个不错的例子 这里,但发现它缺少一些功能。所以……就像所有开发者一样,我们进行调整和添加。
代码
我会包含两组代码,以便您可以看到区别。
这是 Jon 发布的原代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq.Expressions;
using System.Text;
namespace MVC3_RadioButtonList_Helper_Sample
{
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
if (listOfValues != null)
{
// Create a radio button for each item in the list
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
// Create the html string that will be returned to the client
// e.g. <input data-val="true" data-val-required=
// "You must select an option" id="TestRadio_1"
// name="TestRadio" type="radio"
// value="1" /><label for="TestRadio_1">Line1</label>
sb.AppendFormat("<div class=\"RadioButton\">{0}{1}</div>", radio, label);
}
}
return MvcHtmlString.Create(sb.ToString());
}
}
}
这是我更新后的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq.Expressions;
using System.Text;
namespace MVC3_RadioButtonList_Helper_Sample
{
public static class HtmlExtensions
{
public static IEnumerable<SelectListItem> ToSelectList(this Enum enumValue)
{
return from Enum e in Enum.GetValues(enumValue.GetType())
select new SelectListItem
{
Selected = e.Equals(enumValue),
Text = e.ToDescription(),
Value = e.ToString()
};
}
public static string ToDescription(this Enum value)
{
var attributes = (DescriptionAttribute[])value.GetType().GetField(
value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues, Position position = Position.Horizontal)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string fullName = ExpressionHelper.GetExpressionText(expression);
var sb = new StringBuilder();
if (listOfValues != null)
{
// Create a radio button for each item in the list
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("rb_{0}_{1}",
fullName.Replace("[", "").Replace(
"]", "").Replace(".", "_"), item.Value);
// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
//var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
var radio = htmlHelper.RadioButton(fullName, item.Value, item.Selected, new { id = id }).ToHtmlString();
// Create the html string that will be returned to the client
// e.g. <input data-val="true" data-val-required=
// "You must select an option" id="TestRadio_1"
/ name="TestRadio" type="radio"
// value="1" /><label for="TestRadio_1">Line1</label>
sb.AppendFormat("<{2} class=\"RadioButton\">{0}{1}</{2}>",
radio, label, (position == Position.Horizontal ? "span" : "div"));
}
}
return MvcHtmlString.Create(sb.ToString());
}
}
}
区别
他的代码很好,但缺少一些东西。第一点是生成实际项目列表的简单方法。第二点是他没有考虑到包含索引器的模型。使用助手方法解决了第一个问题,而使用 Microsoft 用于查找属性完整名称的相同方法解决了第二个问题。在 id 前面添加“rb_”可以确保 id 名称始终合法。
希望这有帮助,并感谢 Jon 提供了一个很好的助手方法作为起点。
历史
首次发布。