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: