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

  • Home
  • SEARCH
  • 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 8124947
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T06:38:30+00:00 2026-06-06T06:38:30+00:00

I have an Html Helper that converts an Enum into a SelectList like so:

  • 0

I have an Html Helper that converts an Enum into a SelectList like so:

public static HtmlString EnumSelectListFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> forExpression,
    object htmlAttributes,
    bool blankFirstLine) where TModel : class where TProperty : struct
{
    //MS, it its infinite wisdom, does not allow enums as a generic constraint, so we have to check here.
    if (!typeof(TProperty).IsEnum) throw new ArgumentException("This helper method requires the specified model property to be an enum type.");

    //initialize values
    var metaData = ModelMetadata.FromLambdaExpression(forExpression, htmlHelper.ViewData);
    var propertyName = metaData.PropertyName;
    var propertyValue = htmlHelper.ViewData.Eval(propertyName).ToStringOrEmpty();

    //build the select tag
    var returnText = string.Format("<select id=\"{0}\" name=\"{0}\"", HttpUtility.HtmlEncode(propertyName));
    if (htmlAttributes != null)
    {
        foreach (var kvp in htmlAttributes.GetType().GetProperties()
            .ToDictionary(p => p.Name, p => p.GetValue(htmlAttributes, null)))
        {
            returnText += string.Format(" {0}=\"{1}\"", HttpUtility.HtmlEncode(kvp.Key),
                HttpUtility.HtmlEncode(kvp.Value.ToStringOrEmpty()));
        }
    }
    returnText += ">\n";

    if (blankFirstLine)
    {
        returnText += "<option value=\"\"></option>";
    }

    //build the options tags
    foreach (var enumName in Enum.GetNames(typeof(TProperty)))
    {
        var idValue = ((int)Enum.Parse(typeof(TProperty), enumName, true)).ToString();
        var displayValue = enumName;
        var titleValue = string.Empty;
        returnText += string.Format("<option value=\"{0}\" title=\"{1}\"",
            HttpUtility.HtmlEncode(idValue), HttpUtility.HtmlEncode(titleValue));
        if (enumName == propertyValue)
        {
            returnText += " selected=\"selected\"";
        }
        returnText += string.Format(">{0}</option>\n", HttpUtility.HtmlEncode(displayValue));
    }

    //close the select tag
    returnText += "</select>";
    return new HtmlString(returnText);
}

Problem I have is, the Enums can’t have spaces in their names, so you can get some ugly select lists if you have something other than one-word enum values, like so:

public enum EmployeeTypes
{
    FullTime = 1,
    PartTime,
    Vendor,
    Contractor
}

Now, I had the bright idea, “I know! I’ll use DataAnnotations for this!”… so I made my enum look like this:

public enum EmployeeTypes
{
    [Display(Name = "Full Time")]
    FullTime = 1,
    [Display(Name = "Part Time")]
    PartTime,
    [Display(Name = "Vendor")]
    Vendor,
    [Display(Name = "Contractor")]
    Contractor
}

… but now I’m scratching my head how to access those attributes in my helper class. Can someone get me going on this?

  • 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-06-06T06:38:32+00:00Added an answer on June 6, 2026 at 6:38 am

    You could read the DisplayAttribute from the enum field using reflection inside the loop:

    foreach (var enumName in Enum.GetNames(typeof(TProperty)))
    {
        var idValue = ((int)Enum.Parse(typeof(TProperty), enumName, true)).ToString();
        var displayValue = enumName;
    
        // get the corresponding enum field using reflection
        var field = typeof(TProperty).GetField(enumName);
        var display = ((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
        if (display != null)
        {
            // The enum field is decorated with the DisplayAttribute =>
            // use its value
            displayValue = display.Name;
        }
    
        var titleValue = string.Empty;
        returnText += string.Format("<option value=\"{0}\" title=\"{1}\"",
            HttpUtility.HtmlEncode(idValue), HttpUtility.HtmlEncode(titleValue));
        if (enumName == propertyValue)
        {
            returnText += " selected=\"selected\"";
        }
        returnText += string.Format(">{0}</option>\n", HttpUtility.HtmlEncode(displayValue));
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a small helper app that I use to inject scripts into html
I have build a custom Html Helper extension as follows: public static string DatePicker(this
I have an html helper that I'd like to set a default on. @Html.EditorFor(model
I have an html.TextArea helper that I'd like to set a default. @Html.TextAreaFor(model =>
I have a handful of helper methods that convert enum values into a list
I have an HtmlHelper like this: (simplified for clarity) public static MvcHtmlString MyHelper<TModel>(this HtmlHelper<TModel>
I have an HTML Helper that essentially renders static content read from HTML files
I have extended the ASP.NET MVC Html Helper to include my own ValidationImage that
I have an HTML helper that I need to pass an Object to. This
I have an html helper library that I am making and one of my

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.