Setup in .net 4.8 mvc: Model
public class FirstLevel
{
public IEnumerable<SecondLevel> SecondLevelEntities {get;set;}
}
public class SecondLevel
{
public AnEnumType EnumTypeSample {get;set;}
}
public enum AnEnumType
{
noone = 0,
[Display(Name="First one")]
firstone = 1,
[Display(Name="Second one")]
secondone = 2
}
CSHTML
@model Sample.Models.Example.FirstLevel
@if(Model.SecondLevelEntities.Any())
{
@foreach(var entity in Model.SecondLevelEntities)
{
@Html.DropDownList("xyz",EnumHelper.GetSelectList(typeof(AnEnumType), entity.EnumTypeSample), new {@class=.... })
}
}
I am upgrading this to .net 6
@Html.DropDownList("xyz",Html.GetEnumSelectList<AnEnumType>(), new {@class=.... })
I am getting only noone in all my dropdownlist controls. I tried to add extension method and updated cshtml is below for this I got all the display value from enum and the value from entity is getting binded again so if one of the selected value is coming as First one it comes twice in the dropdown.
@Html.DropDownList("xyz",Html.GetEnumSelectList<AnEnumType>(), entity.EnumTypeSample.GetAttribute<DisplayAttribute>().Name, new {@class=.... })
EnumDropDownListFor is not available, I have even tried DropDownListFor but to no avail. I need to bind the display name in my dropdown and the right value should be binded by default only once.
I get your point, Here is a simple demo with hard code, When the page load, dropdown list will show the options which binded in backend:
controller
public IActionResult Hello()
{
FirstLevel first = new FirstLevel();
List<SecondLevel> seconds = new List<SecondLevel>();
seconds.Add(new SecondLevel()
{
EnumTypeSample = AnEnumType.secondone
});
seconds.Add(new SecondLevel()
{
EnumTypeSample = AnEnumType.firstone
});
seconds.Add(new SecondLevel()
{
EnumTypeSample = AnEnumType.firstone
});
first.SecondLevelEntities = seconds;
return View(first);
}
view
@model FirstLevel
@if (Model.SecondLevelEntities.Any())
{
@foreach (var entity in Model.SecondLevelEntities)
{
<select asp-for="@entity.EnumTypeSample" asp-items="Html.GetEnumSelectList<AnEnumType>()">
</select>
}
}