Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1.1k views
in .Net Framework by 39 42 54
edited by

I am working on an MVC solutions and I want to display enum data in a dropdownlist using ViewBag in an MVC view , How can I do that in MVC?

Bind dropdownlist from Enum in MVC


1 Answer

0 like 0 dislike
by 39 42 54
 
Best answer

Displaying Enum Data in a Dropdownlist Using ViewBag in an MVC View

To displaying Enum Data in a dropdownlist Using ViewBag in an MVC View, you should follow the below steps in details:

1- Create enum with name ActionType

public enum ActionType
{
    [Description("تسجيل الدخول")]
    Login = 1 ,

    [Description("إنشاء الطلب")]
    CreateApplication = 2 ,

    [Description("تعديل بيانات الطلب")]
    EditApplication = 3 ,

    [Description("أرشفة المستخدم")]
    DeleteUser = 4 ,

    [Description("إنشاء المستخدم")]
    CreateUser = 5 ,

    [Description("تعديل بيانات المستخدم")]
    EditUser = 6 
}

2- In the controller, you should utilize the following code to retrieve the descriptions from the enum and store the results in the ViewBag for presentation in the View.

ViewBag.TrackingName = Enum.GetValues(typeof(ActionType))
                       .Cast<ActionType>()
                       .Select(e => new SelectListItem
                       {
                           Value = e.ToString(),
                           Text = EnumHelper.GetEnumDescription(e)
                       })
                       .ToList();

3- In the View, you can access the ViewBag to retrieve the descriptions stored as values from the enum in the following code:

<div class="col-md-4">
    @Html.Label(Resources.Labels.LblTrackingName, new { @class = " form-label", @for = "TrackingName" })
    @Html.DropDownList("TrackingName", null, Resources.Labels.SelectFromMenu, new { @id = "TrackingName", @class = "form-control form-select" })
</div>

Code Snippets:


Result:

If you don’t ask, the answer is always NO!
...