ASP.NET MVC 3 - A RadioButtonList for Enum Properties

ASP.NET MVC3 doesn’t have a built-in RadioButtonList helper and there are times that I want to display an Enum property. I can always do that using a dropdown list but if there are 2 or 3 values then it’s more user-friendly if the user sees all the options.

So in a simple yes/no question (which I want to force the user to answer so checkbox isn’t really an option) a prefer this:

image

over this:

image

So what I did was to create a Enum_RadioButtonList.cshtml file inside Views/Shared/EditorTemplates/ with the following code:

@model Enum
@{
    var listItems = Enum.GetValues(Model.GetType()).OfType<Enum>().Select(e =>
    new SelectListItem()
    {
        Text = e.ToString(),
        Value = e.ToString(),
        Selected = e.Equals(Model)
    });
    string prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
    int index = 0;
    ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;
    foreach (var li in listItems)
    {
    string fieldName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_{1}", prefix, index++);
        @Html.RadioButton(prefix, li.Value, li.Selected, new { @id = fieldName })         @Html.Label(fieldName, li.Text)    
    }
    ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
}

And then call it from a page like :

@Html.EditorFor(model => model.EnumProperty, "Enum_RadioButtonList")

So if our Enum was DayOfWeek then we should see something like that:

image

Of course there are other ways to achive that like using UIHint attribute in your Enum or renaming your file to Enum.cshtml so that every Enum renders that way or even creating an HtmlHelper Extension method.

Please do let me know if the above code is not working in a case.

Cheers!

Edit1: You can check out an improved version by Jason Gable.

Edit2: You can check out an event better version by Jeffrey Tummers that supports .resx files

17 Comments

  • ron cyrier on said

    Reply
    




ron cyrier

    Works great. Thanks!

  • 




Ricardo

    :D

  • 




<a href="http://jacob4u2.posterous.com" rel="nofollow">Jacob Gable</a>

    This works great. I added a little bit of code to let you add a [Display(Name="Something With Spaces")] type of attribute for better display of Enums with multiple words.
    $1
    $1https://gist.github.com/973482
    $1
    $1Thanks for the snip.

  • 




djsolid

    Thanks! Post updated!

  • 




<a href="http://blog.thumnet.com" rel="nofollow">Jeffrey Tummers</a>

    I have updated Jacob's code, to support Resource files (*.resx).
    $1
    $1https://gist.github.com/1010654
    $1
    $1Thank you both for sharing!
    $1
    $1

  • 




djsolid

    Thanks! Post Updated!

  • 




Marcus

    Very Nice, thanks alot!

  • 




<a href="http://www.marsstout.com" rel="nofollow">traci</a>

    Hi,
    $1 Could someone tell me how this code would look in a non-razor control. I am trying to convert the code and not getting it to compile. I am new to MVC and really need a radiolist solution for my project.
    $1Any help is appreciated.
    $1Thanks Traci
    $1

  • 




Kourosh

    Hi,
    $1
    $1Thank you for this useful post. when I use your code, I get following error. I am newbie on mvc and don't know why the property must have a value.
    $1
    $1The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DayOfWeek'.
    $1
    $1My ViewModel has a property like this.
    $1
    $1public DayOfWeek Days{ get; set; }
    $1
    $1and i call it in the View like this:
    $1
    $1 @Html.EditorFor(m => m.Days, "Your_RadioButtonList")

  • 




<a href="http://www.ovalsquare.com" rel="nofollow">Ted Jardine</a>

    1) Thanks for this (including the follow-up improvements). Just what I needed!
    $1
    $12) Kouroush: you're probably returning a null model to your view. I.e. in your controller action, you probably have:
    $1
    $1return View();
    $1
    $1You need (at least):
    $1
    $1return View(new WhateverYourViewModelIs());
    $1
    $1...and that'll take care of your issue.

  • 




<a href="http://blogs.sonatribe.com/wayne" rel="nofollow">wayne</a>

    How would i make this work with nullable enums?

  • 




Romiko

    Hi,
    $1
    $1Indeed, How can we get this to work with Nullable Enums?

  • 




Gary

    It's the bested solution i had ever seen for the radio button list. Thanks.
    $1
    $1
    $1to RomikoReply:
    $1you can new an empty modul to this view.
    $1

  • 




Neox

    I have updated function, to support resource files - now you can add your resource Name.
    $1
    $1Func<enum, string=""> getDescription = en =>
    $1 {
    $1 Type type = null;
    $1 System.Reflection.MemberInfo[] memInfo = null;
    $1 try
    $1 {
    $1 type = en.GetType();
    $1 memInfo = type.GetMember(en.ToString());
    $1
    $1 if (memInfo != null && memInfo.Length > 0)
    $1 {
    $1 return Resources.ResourceManager.GetString(string.Format("SystemEnum_{0}_{1}", type.Name, memInfo[0].Name), Resources.Culture);
    $1 }
    $1 }
    $1 catch { }
    $1 return en.ToString();
    $1 };
    $1
    $1Internationalization (globalization and localization) is here: http://afana.me/post/aspnet-mvc-internationalization-part-2.aspx
    $1
    $1NEOX</enum,>

  • 




diego

    great example how can i use for my edit view, as in my edit view I will know which day is selected in the radiobutton previosly

  • 




diego

    ok I figure out how to do it, ty great example

  • electric glass insulators on said

    Reply
    




electric glass insulators

    I definitely desired to deliver a quick concept to thank you for the nice tips and hints you're posting on djsolid.net . My time-consuming internet appear up has now been rewarded with helpful strategies to exchange with my family and friends. I'd claim that we readers fact are truly blessed to dwell in a helpful community with incredibly some great individuals with insightful points. I really feel really grateful to get discovered the webpage and appear ahead to a lot of additional entertaining moments reading right here. Thanks a good deal again for a good deal of things.

Add a Comment (gravatar-enabled)