在ASP.NETMVC3中,经常需要在视图中创建单选按钮列表(RadioButtonList)。Jon Lanceley在其博客上分享了一个创建RadioButtonList的示例代码,但发现它缺少了一些功能。因此,对其进行了改进和扩展。
以下是Jon Lanceley最初发布的代码示例:
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(
thisHtmlHelper htmlHelper,
Expression> expression,
IEnumerable listOfValues)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
if (listOfValues != null)
{
foreach (SelectListItem item in listOfValues)
{
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
sb.AppendFormat("{0}{1}", radio, label);
}
}
return MvcHtmlString.Create(sb.ToString());
}
}
}
这段代码使用HtmlHelper扩展方法来创建RadioButtonList。它遍历一个SelectListItem集合,并为每个项创建一个单选按钮和一个标签。
对原始代码进行了改进,增加了以下功能:
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 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(
thisHtmlHelper htmlHelper,
Expression> expression,
IEnumerable listOfValues, Position position = Position.Horizontal)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string fullName = ExpressionHelper.GetExpressionText(expression);
var sb = new StringBuilder();
if (listOfValues != null)
{
foreach (SelectListItem item in listOfValues)
{
var id = string.Format("rb_{0}_{1}", fullName.Replace("[", "").Replace("]", "").Replace(".", "_"), item.Value);
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = htmlHelper.RadioButton(fullName, item.Value, item.Selected, new { id = id }).ToHtmlString();
sb.AppendFormat("<{2} class=\"RadioButton\">{0}{1}", radio, label, (position == Position.Horizontal ? "span" : "div"));
}
}
return MvcHtmlString.Create(sb.ToString());
}
}
}