0

Controller

        public ActionResult Index()
        {
            var view = new FruitVM();
            ViewBag.SelectFruitList = GetFruitList();
            return View(view);
        }
        public List<SelectListItem> GetFruitList()
        {
            List<SelectListItem> selectListItems = new List<SelectListItem>();
            selectListItems.Add(new SelectListItem { Text = "Apple", Value = "1"});
            selectListItems.Add(new SelectListItem { Text = "Orange", Value = "2" });
            selectListItems.Add(new SelectListItem { Text = "Banana", Value = "3" });
            selectListItems.Add(new SelectListItem { Text = "Others", Value = "0" });
            return selectListItems;
        }

Index

<div class="form-group">
    <label class="col-sm-3">Pick Fruit</label>
        <div class="col-sm-6">
            @foreach (var item in (List<SelectListItem>)ViewBag.SelectFruitList)
                {
                <label class="checkbox-inline"><input type="checkbox" value="@item.Value" name="Fruit">@item.Text </label>
                }
        </div>
</div>

Enum

    public enum EnumFruits
    {
        [Description("Apple")]
        A = 1,
        [Description("Orange")]
        B = 2,
        [Description("Banana")]
        C = 3,
        [Description("Others")]
        O = 0,
    }

How can I use Enum instead of hardcoding it, Some of the post at here is for the dropdownlist but I wanted to append checkboxes instead of dropdownlist. Is it possible to do it.

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
FENR1R Ace
  • 68
  • 9

2 Answers2

0

Live demo here


public static string GetEnumDescription(Enum value)
{
    var fi = value.GetType().GetField(value.ToString());

    var attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];

    if (attributes != null && attributes.Any())
    {
        return attributes.First().Description;
    }

    return value.ToString();
}   

var selectListItems  = Enum.GetValues(typeof(EnumFruits))
    .Cast<EnumFruits>()
    .Select(v => new SelectListItem { Text = GetEnumDescription((EnumFruits)v), Value = (int)v } )
    .ToList();

enter image description here

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0

You need extension method to get description from enum.

var selectListItems  = Enum.GetValues(typeof(EnumFruits))
    .Cast<EnumFruits>()
    .Select(v => new SelectListItem { Text = v.GetDescription(), Value = (int)v })
    .ToList();

public static class EnumExtensions
{
    private static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
    {
        var type = value?.GetType();
        if (type == null)
            return default;
        var name = Enum.GetName(type, value);
        return type.GetRuntimeField(name)?.GetCustomAttributes(false)
            .OfType<TAttribute>().SingleOrDefault();
    }
    
    public static string GetDescription(this Enum value)
    {
        return value?.GetAttribute<DescriptionAttribute>()?.Description;
    }
    
    public static string GetDescription(this Enum value, params object[] args)
    {
        return string.Format(value?.GetAttribute<DisplayAttribute>()?.Name ?? string.Empty, args);
    }
}
  • A quick question is it possible to make it as a public function, because I need to call this a few time within the same controller. Bcs wanted to prevent repeat code – FENR1R Ace Feb 02 '21 at 04:53
  • Sure you can, you can also cache resulting list in static variable for performance reasons. – Alexey Rumyantsev Feb 02 '21 at 05:14