Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7073159
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T05:53:45+00:00 2026-05-28T05:53:45+00:00

I’m currently using this for turning an enum into a radio control, public static

  • 0

I’m currently using this for turning an enum into a radio control,

public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression)
{
    var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

    var sb = new StringBuilder();
    var enumType = metaData.ModelType;
    foreach (var field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
    {
        var value = (int)field.GetValue(null);
        var name = Enum.GetName(enumType, value);
        var label = name;
        foreach (DisplayAttribute currAttr in field.GetCustomAttributes(typeof(DisplayAttribute), true))
        {
            label = currAttr.Name;
            break;
        }

        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(label),
            radio
        );
    }
    return MvcHtmlString.Create(sb.ToString());
}

but when trying to adapt it to enum to dropdown:

public static MvcHtmlString DropDownListForEnum<TModel, TProperty>(
   this HtmlHelper<TModel> htmlHelper,
   Expression<Func<TModel, TProperty>> expression)
{
     var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

     var sb = new StringBuilder();
     var enumType = metaData.ModelType;
     sb.Append("<select name=\"" + metaData.PropertyName + "\" id=\"" + metaData.PropertyName + "\" > ");
     foreach (var field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
     {
          var value = (int)field.GetValue(null);
          var name = Enum.GetName(enumType, value);
          var label = name;

          foreach (DisplayAttribute currAttr in field.GetCustomAttributes(typeof(DisplayAttribute), true))
          {
                label = currAttr.Name;
                break;
          }

          var id = string.Format(
                    "{0}_{1}_{2}",
                    htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
                    metaData.PropertyName,
                    name
                );
          var listitem = htmlHelper.DropDownListFor(expression, name, new { id = id }).ToHtmlString();
          sb.AppendFormat(
                    "<option value=\"{0}_{1}\">{2}</option> ",
                    id,
                    listitem,
                    HttpUtility.HtmlEncode(label)
                );
     }
     sb.Append("</select>");
     return MvcHtmlString.Create(sb.ToString());
}

I get an error in the var listitem = htmlHelper.DropDownListFor line. Basically I’m not providing the correct information in the method. Could anyone shed any light on this issue?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T05:53:46+00:00Added an answer on May 28, 2026 at 5:53 am

    You can use a static helper that turns enums into select lists.

    I’ve blogged about it here:

    http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23

    The helper (this will get the value of the description attribute if present):

    public static class EnumHelper
    {
        public static SelectList SelectListFor<T>(T? selected)
            where T : struct
        {
            return selected == null ? SelectListFor<T>()
                                    : SelectListFor(selected.Value);
        }
    
        public static SelectList SelectListFor<T>() where T : struct
        {
            Type t = typeof (T);
            if (t.IsEnum)
            {
                var values = Enum.GetValues(typeof(T)).Cast<Enum>()
                                 .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
    
                return new SelectList(values, "Id", "Name");
            }
            return null;
        }
    
        public static SelectList SelectListFor<T>(T selected) where T : struct 
        {
            Type t = typeof(T);
            if (t.IsEnum)
            {
                var values = Enum.GetValues(t).Cast<Enum>()
                                 .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
    
                return new SelectList(values, "Id", "Name", Convert.ToInt32(selected));
            }
            return null;
        }
    
        public static string GetDescription<TEnum>(this TEnum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
    
            if (fi != null)
            {
                DescriptionAttribute[] attributes =
                    (DescriptionAttribute[])fi.GetCustomAttributes(
                        typeof(DescriptionAttribute),
                        false);
    
                if (attributes.Length > 0)
                    return attributes[0].Description;
            }
    
            return value.ToString();
        }
    }
    

    This helper will enable you to convert an enum to a select list in just two lines.

    In your controller:

    ViewBag.TypeDropDown = EnumHelper.SelectListFor(field);
    

    In your view:

    @Html.DropDownList("TypeDropDown")
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I am currently running into a problem where an element is coming back from
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
public static bool CheckLogin(string Username, string Password, bool AutoLogin) { bool LoginSuccessful; // Trim
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I am reading a book about Javascript and jQuery and using one of the
I want use html5's new tag to play a wav file (currently only supported

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.