pass enum to html.radiobuttonfor MVC3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace YourNamespace
{
    public static class HtmlExtensions
    {
        public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression
        )
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var names = Enum.GetNames(metaData.ModelType);
            var sb = new StringBuilder();
            foreach (var name in names)
            {
                var id = string.Format(
                    "{0}_{1}_{2}", 
                    htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, 
                    metaData.PropertyName, 
                    name
                );

                var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();
                sb.AppendFormat(
                    "<label for=\"{0}\">{1}</label> {2}", 
                    id, 
                    HttpUtility.HtmlEncode(name), 
                    radio
                );
            }
            return MvcHtmlString.Create(sb.ToString());
        }
    }
}    

You could also enforce a generic constraint to an enum type for this helper method.

and then:

Model:

public enum ActionStatus
{
    Open,
    Closed
}

public class MyViewModel
{
    public ActionStatus Status { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Status = ActionStatus.Closed
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.RadioButtonForEnum(x => x.Status)
    <input type="submit" value="OK" />
}

Leave a Comment