locked
Hide value of enum from the html (UI) RRS feed

  • Question

  • User-560223997 posted

    I have an enum type like:

        public enum EntryState
        {
            Proposed = 0x0001,
            Canceled = 0x0002,
                Approved = 0x0004,    // for compatibility only!
            [Display(Name = "--Authorized--")]
            Authorized = 0x0004,
            Repproved = 0x0008,
            All= Proposed| Canceled | Authorized | Repproved
        }
    

    and I render it in the html as:

    @Html.DropDownListFor(m => m.AppStateData.state, Html.GetEnumSelectList<EntryState>(), new { @class = "dstate-control" })
    

    This will show the values in the enum, including 2 with the same value (Approved , Authorized ).

    However, I only include Approved for compatibility, and I wouldn't like to render this tag in the html (UI).

    Could you help me?

    Thursday, June 18, 2020 5:08 PM

Answers

All replies

  • User753101303 posted

    Hi,

    You could use https://docs.microsoft.com/en-us/dotnet/api/system.obsoleteattribute?view=netcore-3.1 to mark this value and maybe use your own GetEnumSelectList.

    Or if I remember you can define a custom metadaprovider that would skip obsoleted enum values.

    Edit: see for example http://www.reza-aghaei.com/customize-asp-net-mvc-model-metadata/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 18, 2020 7:19 PM
  • User2078676645 posted

    Hi,

    You can add where condition judgment after GetEnumSelectList.

    @Html.DropDownListFor(m => m.AppStateData.state, Html.GetEnumSelectList<EntryState>().Where(x=>x.Text!= "Approved"), new { @class = "dstate-control" })

    Or you can add other logic according to your needs.

    Regards,

    Evern

    Friday, June 19, 2020 1:32 AM
  • User-560223997 posted

    Hi,

    So, I flagged the values of the enum with [Obsolete] in the definition of the enum.

    However, when I try to use this flag in the view with:

    var l = typeof(EntryState).GetMembers().Where(l => l.GetCustomAttributes(typeof(ObsoleteAttribute),false).Length == 0);
    

    I obtain also the methods associated to the enum... Do you know how I can get only the values (and not the methods and others)?

    Friday, June 19, 2020 9:54 AM