Get Enum value from description in ASP.Net MVC

mahesh213
 
on Apr 13, 2022 01:05 AM
Sample_729610.zip
677 Views

Hi,

I have list of string values form based upon those values need to get those values and return those values in method.

can you please help me

public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes,
    [Description("Call me back in 10 minutes!")]
    In10Minutes
}

 

public CancelReasonsEnum GetEnumvaluesFromString()
{
    List<string> values = new List<string>() { "Need more coffee", "Call me back in 5 minutes!" };
    //get enumn values based upon list of string values
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Apr 13, 2022 05:34 AM

Refer below code.

public List<CancelReasonsEnum> GetEnumvaluesFromString()
{
    List<string> values = new List<string>() { "Need more coffee", "Call me back in 5 minutes!" };
    List<CancelReasonsEnum> enumValues = new List<CancelReasonsEnum>();
    foreach (string item in values)
    {
        enumValues.Add((CancelReasonsEnum)GetEnumFromDescription(item, typeof(CancelReasonsEnum)));
    }

    return enumValues;
}

public static int GetEnumFromDescription(string description, Type enumType)
{
    foreach (var field in enumType.GetFields())
    {
        DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
        if (attribute == null)
            continue;
        if (attribute.Description == description)
        {
            return (int)field.GetValue(null);
        }
    }
    return 0;
}

public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes,
    [Description("Call me back in 10 minutes!")]
    In10Minutes
}

Screenshot