Using enum for dropdown list in ASP.NET MVC Core

為{幸葍}努か 提交于 2019-12-02 18:42:35
Kostas

I think you accidentally used GenderType instead of Gender. The correct syntax is

<select asp-for="GenderType" asp-items="Html.GetEnumSelectList<Gender>()">
    <option selected="selected" value="">Please select</option>
</select>

GenderType is your property name, not the Enum type. The GetEnumSelectList method expects you to give it the type of the Enumeration, not the name of the property in your model.

Try this:

Html.GetEnumSelectList<Gender>()
Faishal Ahammad

You can simply use Razor syntax:

@Html.DropDownList("StudentGender", 
    Html.GetEnumSelectList<Gender>(),
    "Select Gender",new { @class = "form-control" })
Rogerio Azevedo

I got the same problem, I burned my head looking for a solution!

You can solve this situation, instantiating you model on top of your view like:

@using CRM.Model;

@using YourSolution.Model

Yes, it sounds too strange but belive me, it works! See my answer on my own post.

Select ENUM Tag Helper in ASP.NET Core MVC

you use Gender to asp-items="Html.GetEnumSelectList -GenderType- ()" instead of GenderType

such as asp-items="Html.GetEnumSelectList -Gender- ()"

The below was what worked for me. This is necessary and the way it is because the enum itself is a class declared under the scope of the class which you are using as a model.

<select asp-for="Status" class="form-control" asp-items="@Html.GetEnumSelectList<Cart.CartStatus>()"></select>

below my model (work in progress) for reference

 public class Cart
    {
        public int CartId { get; set; }
        public List<Order> Orders { get; set; }
        [Required]
        public string UserId { get; set; }
        public DateTime DeliveryDate { get; set; }
        public CartStatus Status { get; set; }
        public enum CartStatus
        {
            Open = 1,
            Confirmed = 2,
            Shipped = 3,
            Received = 4
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!