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 4024650
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T10:44:52+00:00 2026-05-20T10:44:52+00:00

I wrote a helper method to display enums from my model in my asp.net

  • 0

I wrote a helper method to display enums from my model in my asp.net MVC application as drop down lists in my views.

Here is my code for that:

public static List<SelectListItem> CreateSelectItemList<TEnum>(object enumObj,
                                                            string defaultItemKey,
                                                            bool sortAlphabetically,
                                                            object firstValueOverride)
    where TEnum : struct
    {
        var values = (from v in (TEnum[])Enum.GetValues(typeof(TEnum))
                      select new
                      {
                          Id = Convert.ToInt32(v),
                          Name = ResourceHelpers.GetResourceValue(AppConstants.EnumResourceNamespace,
                                                                  typeof(TEnum).Name, v.ToString())
                      });


        return values.ToSelectList(e => e.Name,
                                               e => e.Id.ToString(),
                                               !string.IsNullOrEmpty(defaultItemKey) ? ResourceHelpers.GetResourceValue(AppConstants.EnumResourceNamespace, defaultItemKey) : string.Empty,
                                               enumObj,
                                               sortAlphabetically,
                                               firstValueOverride);

    }

This actually generates the select item list:

public static List<SelectListItem> ToSelectList<T>(
    this IEnumerable<T> enumerable,
    Func<T, string> text,
    Func<T, string> value,
    string defaultOption,
    object selectedVal,
    bool sortAlphabetically,
    object FirstValueOverride)
{

    int iSelectedVal = -1;

    if(selectedVal!=null)
    {
        try
        {
            iSelectedVal = Convert.ToInt32(selectedVal);
        }
        catch
        {
        }
    }

    var items = enumerable.Select(f => new SelectListItem()
    {
        Text = text(f),
        Value = value(f),
        Selected = (iSelectedVal > -1)? (iSelectedVal.ToString().Equals(value(f))) : false
    });

    #region Sortare alfabetica
    if (sortAlphabetically)
        items = items.OrderBy(t => t.Text);
    #endregion Sortare alfabetica

    var itemsList = items.ToList();

    Func<SelectListItem, bool> funct = null;
    string sValue = string.Empty;
    SelectListItem firstItem = null;
    SelectListItem overridenItem = null;
    int overridenIndex = 0;

    if (FirstValueOverride != null)
    {
        sValue = FirstValueOverride.ToString();

        funct = (t => t.Value == sValue);
        overridenItem = itemsList.SingleOrDefault(funct);
        overridenIndex = itemsList.IndexOf(overridenItem);

        if (overridenItem != null)
        {
            firstItem = itemsList.ElementAt(0);
            itemsList[0] = overridenItem;
            itemsList[overridenIndex] = firstItem;
        }
    }

    if(!string.IsNullOrEmpty(defaultOption))
        itemsList.Insert(0, new SelectListItem()
        {
            Text = defaultOption,
            Value = "-1"
        });

    return itemsList;
}

These is the method I call:

        public static MvcHtmlString EnumDropDownList<TEnum>(this HtmlHelper htmlHelper, 
                                                        object enumObj,
                                                        string name,
                                                        string defaultItemKey,
                                                        bool sortAlphabetically,
                                                        object firstValueOverride,
                                                        object htmlAttributes)
    where TEnum : struct
    {
        return htmlHelper.DropDownList(name,
                                        CreateSelectItemList<TEnum>(enumObj,
                                                                defaultItemKey,
                                                                sortAlphabetically,
                                                                firstValueOverride), 
                                         htmlAttributes);
    }

Now I am having the problem described here
When I call this helper method and the input’s name is the same as the property’s name the selected value doesn’t get selected.
The alternate solution described there doesn’t work for me. The only solution that works is changing the name and not using the model binding using FormCollection instead.
I don’t like this workaround because I can’t use validation any more using the ViewModel pattern and I have to write some extra code for every enum.
I tried writing a custom model binder to compensate for this somehow but none of the methods I can override there gets called when I start the action.

Is there any way to do this without using FormCollection?
Can I somehow intercept ASP.NET MVC when it tries to put the value into my input field and make it select the right value?

Thank you in advance.

  • 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-20T10:44:52+00:00Added an answer on May 20, 2026 at 10:44 am

    I have a sollution now
    Here is the code for the EnumDropDownList function the other functions are listed in the question:

    public static MvcHtmlString EnumDropDownList(this HtmlHelper htmlHelper,
                                                       object enumObj,
                                                       string name,
                                                       string defaultItemKey,
                                                       bool sortAlphabetically,
                                                       object firstValueOverride,
                                                       object htmlAttributes)
    {
    
        StringBuilder sbRezultat = new StringBuilder();
    
        int selectedIndex = 0;
    
        var selectItemList = new List<SelectListItem>();
    
    
        if (enumObj != null)
        {
            selectItemList = CreateSelectItemList(enumObj, defaultItemKey, true, null);
    
            var selectedItem = selectItemList.SingleOrDefault(item => item.Selected);
            if (selectedItem != null)
            {
                selectedIndex = selectItemList.IndexOf(selectedItem);
    
            }
        }
    
        var dict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    
    
        TagBuilder tagBuilder = new TagBuilder("select");
    
        tagBuilder.MergeAttribute("name", name,true);
    
        bool bReadOnly = false;
    
        //special case for readonly
        if(dict.ContainsKey("readonly"))
        {
            //remove this tag it won't work the way mvc renders it anyway
            dict.Remove("readonly");
            bReadOnly = true;
        }
    
        //in case the style element is completed if the drop down is not readonly
        tagBuilder.MergeAttributes(dict, true);
    
        if (bReadOnly)
        {
            //add a small javascript to make it readonly and add the lightgrey style
            tagBuilder.MergeAttribute("onchange", "this.selectedIndex=" + selectedIndex + ";",true);
            tagBuilder.MergeAttribute("style", "background: lightgrey", true);
        }
    
        sbRezultat.Append(tagBuilder.ToString(TagRenderMode.StartTag));
    
    
        foreach (var option in selectItemList)
        {
            sbRezultat.Append(" <option value='");
            sbRezultat.Append(option.Value);
            sbRezultat.Append("' ");
            if (option.Selected)
                sbRezultat.Append("selected");
            sbRezultat.Append(" >");
            sbRezultat.Append(option.Text);
    
    
            sbRezultat.Append("</option>");
        }
        sbRezultat.Append("</select>");
        return new MvcHtmlString(sbRezultat.ToString());
    }
    

    I also wrote a generic function of type For (EnumDropDownFor):

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
                                    string defaultItemKey,
                                    bool sortAlphabetically,
                                    object firstValueOverride,
                                    object htmlAttributes)
        where TProperty : struct
    {
        string inputName = GetInputName(expression);
    
        object selectedVal = null;
        try
        {
            selectedVal = htmlHelper.ViewData.Model == null
                ? default(TProperty)
                : expression.Compile()(htmlHelper.ViewData.Model);
        }
        catch//in caz ca e ceva null sau ceva de genu'
        {
        }
    
        return EnumDropDownList(htmlHelper,
                                selectedVal,
                                inputName,
                                defaultItemKey,
                                sortAlphabetically,
                                firstValueOverride,
                                htmlAttributes);
    }
    

    and some helper methods:

    public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
    {
        if (expression.Body.NodeType == ExpressionType.Call)
        {
            MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
            string name = GetInputName(methodCallExpression);
            return name.Substring(expression.Parameters[0].Name.Length + 1);
    
        }
        return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
    }
    
    private static string GetInputName(MethodCallExpression expression)
    {
        MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression;
        if (methodCallExpression != null)
        {
            return GetInputName(methodCallExpression);
        }
        return expression.Object.ToString();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am creating LOB business application using ASP.NET MVC. In my views I find
I use templated helpers in an ASP.NET MVC 3 project. One display template had
I'm working on an asp.net MVC application. I have a class that wraps a
I'm trying out ASP.NET MVC Framework and would like to create an ajax helper
I have an ASP.NET WebForms control (derived from Control, not WebControl, if it helps)
I wrote an instance method in my model for calculating a time difference between
I am using ASP.NET MVC 3 and NUnit . I am trying to write
Lets say i wrote helper for TStringList TslHelper = class helper for TStringList function
I wrote my code using this article at msdn as a primary helper My
Often I need to combine data from multiple tables and display the result in

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.