问题
I'm trying to create a dropdown list with an enum property in ASP.NET MVC Core using the tag helper in a Razor view:
Here is the model:
public class PersonalMember : Member
{
[Required, Display(Name = "First Name")]
public string FirstName { get; set; }
[Required, Display(Name = "Last Name")]
public string LastName { get; set; }
[EnumDataType(typeof(Gender))]
public Gender GenderType { get; set; }
}
public enum Gender
{
Male = 1,
Female = 2
}
Here is part of a form in the view:
<div class="form-group">
<label asp-for="GenderType" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="GenderType" asp-items="Html.GetEnumSelectList<GenderType>()">
<option selected="selected" value="">Please select</option>
</select>
<span asp-validation-for="GenderType" class="text-danger" />
</div>
</div>
The problem I'm having is that after Html.GetEnumSelectList
, GenderType
is not recognized and shows up as an error.
Does anyone know how to solve this?
回答1:
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>
回答2:
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>()
回答3:
You can simply use Razor syntax:
@Html.DropDownList("StudentGender",
Html.GetEnumSelectList<Gender>(),
"Select Gender",new { @class = "form-control" })
回答4:
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
回答5:
you use Gender to asp-items="Html.GetEnumSelectList -GenderType- ()" instead of GenderType
such as asp-items="Html.GetEnumSelectList -Gender- ()"
回答6:
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
}
}
来源:https://stackoverflow.com/questions/41740638/using-enum-for-dropdown-list-in-asp-net-mvc-core