简体   繁体   English

隐式枚举到core2.1剃须刀页面中的下拉列表

[英]Covert enum to dropdown list in core2.1 razor pages

i have the following enum 我有以下枚举

public class Blog {

   public enum BlogType {
     Article,
     News
   }

}

i want to convert it to drop down list, but i get error : Cannot implicitly convert type 'Blog.BlogType' to 'System.Collections.Generic.IEnumerable 我想将其转换为下拉列表,但出现错误: 无法将类型'Blog.BlogType'隐式转换为'System.Collections.Generic.IEnumerable

my code : 我的代码:

IList<SelectListItem> list = Enum.GetValues(typeof(Blog.BlogType))
.Cast<Blog.BlogType>()
.Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() })
.ToList();

SelectList data = new SelectList(list, "Value", "Text");

i tried several solutions but i got the same issue.. 我尝试了几种解决方案,但我遇到了同样的问题。

thanks .. 谢谢 ..

The easiest way to do this is to use the Html.GetEnumSelectList<TEnum> method in a select tag helper: 最简单的方法是在选择标记帮助器中使用Html.GetEnumSelectList<TEnum>方法:

<select asp-for="BlogType" asp-items="Html.GetEnumSelectList<BlogType>()">
    <option value="">Pick one</option>
</select>

See more about using the select tag helper and enumerations in Razor Pages here: https://www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper#enumerations 在此处查看有关在Razor Pages中使用选择标记帮助器和枚举的更多信息: https : //www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper#enumerations

试试这个代码

  Html.DropDownListFor(o => o.EnumProperty, Enum.GetValues(typeof(Blog)).Cast<Blog>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM