Skip to content

Instantly share code, notes, and snippets.

@jasmin-mistry
Created January 28, 2014 13:40
Show Gist options
  • Save jasmin-mistry/8667834 to your computer and use it in GitHub Desktop.
Save jasmin-mistry/8667834 to your computer and use it in GitHub Desktop.
public static partial class MyEnumRadioButtonList
{
#region Enum Radio Button List
public static MvcHtmlString EnumRadioButtonListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TEnum>> expression)
{
return EnumRadioButtonListFor(htmlHelper, expression, null);
}
public static MvcHtmlString EnumRadioButtonListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetNonNullableModelType(metadata);
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
string fullName = ExpressionHelper.GetExpressionText(expression);
IEnumerable<SelectListItem> items = from value in values
select new SelectListItem
{
Text = GetEnumDescription(value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
};
var sb = new StringBuilder();
foreach (var item in items)
{
// Generate an id to be given to the radio button field
var id = string.Format("rbl_{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=\"radiobuttonlist\">{0}{1}</{2}>",
// radio, label, (position == Position.Horizontal ? "span" : "div"));
sb.AppendFormat("{0}{1}", radio, label);
}
return MvcHtmlString.Create(string.Format("{0}{1}{2}",
"<span class='radiobuttonlist'>", sb.ToString(), "</span>"));
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment