mar*_*tch 6 razor asp.net-core-mvc asp.net-core
我有一些国家的枚举:
public enum Countries
{
USA,
Canada,
Mexico,
}
Run Code Online (Sandbox Code Playgroud)
然后我在我的模型上有一个属性:
[Required]
public string Country { get; set; }
Run Code Online (Sandbox Code Playgroud)
在我看来,我有:
@Html.DropDownList("Country", Html.GetEnumSelectList(typeof(Countries)) ...)
Run Code Online (Sandbox Code Playgroud)
我想value每一个option在生成select是从每个项目的名称Countries enum.默认情况下,该值是从零开始的整数.
fre*_*n-m 10
这些值是从零开始的整数,因为您已经要求输出枚举的EnumSelectList(即int值).
相反,您可以获取枚举名称列表,例如:
@Html.DropDownList("Country", new SelectList(Enum.GetNames(typeof(Countries))) ... )
Run Code Online (Sandbox Code Playgroud)
这对我有用:
public class Country
{
[Key]
public int Id { get; set; }
[Required]
public CountryFrom CountryFrom { get; set; }
[Required]
[StringLength (100, ErrorMessage = "Name has to be less then 100 symbols long")]
public string Region { get; set; }
public virtual ICollection<Wine> Wines { get; set; }
}
public enum CountryFrom
{
France, Germany, Italy, Spain, Portugal, UK, India, Bulgaria, Other
}
Run Code Online (Sandbox Code Playgroud)
在视图中插入此内容,不要忘记导入
<div class="form-group">
<label asp-for="CountryFrom" class="col-md-2 control-label"></label>
<select asp-for="CountryFrom" asp-items="@Html.GetEnumSelectList<CountryFrom>()" class="form-control"></select>
</div>
Run Code Online (Sandbox Code Playgroud)
我希望它会有所帮助.
这将帮助您获得一个下拉列表,其中包含从枚举中获取的数据,并显示每个项目的名称.
| 归档时间: |
|
| 查看次数: |
4434 次 |
| 最近记录: |