Because it only knows the values, not the text.
Why is using GetEnumSelectList mandatory?
Why do I have to specify the items for a select control targeting an enumerated value explicitly? I would expect the tag helper to populate it for me.
4 answers
Sort by: Most helpful
-
-
AgaveJoe 28,371 Reputation points
2021-11-29T22:04:17.363+00:00 The control is bound to a field of an enumerated type. The renderer can examine the type and extract the values from it.
I understand your point but the tag helpers don't work that way. The asp-for tag helper maps the HTML input name to the model property name. This is used in model binding. The asp-items tag helper expects a collection of SelectListItem which is used to render the select options. The Html.GetEnumSelectList is a convenient way to convert an enumeration (named constant) to a IEnumerable<SelectListItem>.
Similarly, you can use the SelectList(IEnumerable, String, String) constructor to populate select options from a custom collection.
-
Zhi Lv - MSFT 32,336 Reputation points Microsoft Vendor
2021-12-03T06:47:14.22+00:00 The Built-in ASP.NET Core Tag Helpers doesn't contain the specific tag helper to directly render the Enum (without using the
<select>
tag and the GetEnumSelectList method). If you expect the tag helper for the enum type, you could submit feedback at the end of the tag helpers document.It's often convenient to use
<select>
with anenum
property and generate theSelectListItem
elements from theenum
values. TheGetEnumSelectList
method generates aSelectList
object for an enum. More detail information, see: Enum bindingIf you don't want to use the
<select>
tag, you can try to create a custom tag helper to display the enum. Refer to the following articles:Creating Custom Tag Helpers With ASP.NET Core MVC
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.Best regards,
Dillion -
Bruce (SqlWork.com) 65,476 Reputation points
2022-02-17T17:28:24.623+00:00 the select tag helper is used to generate the select.
the asp-for sets the binding string via an expression tree. this is just a syntax tree, and the datatype is not specified
the asp-items is used to generate the options list. asp-items expects an IEnumable<SelectListItem>there are a lot of helpers to generate Items (option list). one is the GetEnumSelectList, but there are others.
at render time, the only way for the tag helper to get the datatype is to bind to the model which may be null, making generic defaults difficult.