-
Notifications
You must be signed in to change notification settings - Fork 0
06 Create DropdownList from Enum
M. Fares edited this page Mar 20, 2018
·
3 revisions
The default scaffolding process creates a textbox for properties of enum type. This procedure changes the textbox to dropdownlist when creating a view with the scaffolding.
- Uder /views/Shared create a folder named DisplayTemplates
- Right click on the created folder and a view named Enum.cshtml
- Remove the content of the view add the following code:
@model Enum
@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata))
{
// Display Enum using same names (from [Display] attributes) as in editors
string displayName = null;
foreach (SelectListItem item in EnumHelper.GetSelectList(ViewData.ModelMetadata, (Enum)Model))
{
if (item.Selected)
{
displayName = item.Text ?? item.Value;
}
}
// Handle the unexpected case that nothing is selected
if (String.IsNullOrEmpty(displayName))
{
if (Model == null)
{
displayName = String.Empty;
}
else
{
displayName = Model.ToString();
}
}
@Html.DisplayTextFor(model => displayName)
}
else
{
// This Enum type is not supported. Fall back to the text.
@Html.DisplayTextFor(model => model)
}- Add the code in your view for the property with enum type.
<div class="form-group">
@Html.LabelFor(model => model.Level, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EnumDropDownListFor(model => model.Level, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Level, "", new { @class = "text-danger" })
</div>
</div>