简体   繁体   English

如何从具有不同名称的剃须刀页面中的 ENUM 创建下拉列表?

[英]How to create dropdown list from a ENUM in razor pages with different name?

I am using razor pages Enum:我正在使用剃须刀页面枚举:

public enum CustomersFilter
{
    Unassigned,
    Unverified_Mobile = 1,
    Unverified_Email = 2,
    Both = 3,
}

payload:有效载荷:

public class UnverifiedCustomersPayload
{
    public CustomersFilter Status { get; set; } = CustomersFilter.Unassigned;
    public IEnumerable<CustomersFilter> FilterableStatus { get; }

    public UnverifiedCustomersPayload()
    {
        FilterableStatus = Enum
                            .GetValues(typeof(CustomersFilter))
                            .Cast<CustomersFilter>()
                            .Where(o => o > CustomersFilter.Unassigned);

    }

public UnverifiedCustomersPayload Filters { get; set; }

HTML: HTML:

                        <select class="form-control"
                                asp-for="Filters.Status"
                                asp-items="@(new SelectList(Model.Filters.FilterableStatus))">
                            <option value="0">None</option>
                        </select>

I am getting data and names but with names Unverified_Email and Unverified_Mobile我正在获取数据和名称,但名称为Unverified_EmailUnverified_Mobile

but I need them as Mobile Unverified and Mobile Unverified但我需要它们作为未验证的移动设备和未验证的移动设备

How can I do that?我怎样才能做到这一点?

Add Display Attribute to them:为它们添加显示属性

using System.ComponentModel.DataAnnotations;

public enum CustomersFilter
{
    Unassigned,
    [Display(Name="Unverified Mobile")]
    Unverified_Mobile = 1,
    [Display(Name="Unverified Email")]
    Unverified_Email = 2,
    Both = 3,
}

If you will use the Display attribute then not necessary to define the <option value="0">None</option> .如果您将使用Display属性,则无需定义<option value="0">None</option> The Unassigned value already set to 0 value by default.默认情况下, Unassigned的值已设置为0值。 Therefore it's necessary only add a description for it.因此,只需为其添加描述即可。

public enum CustomersFilter
{
    [Display(Name = "None")]
    Unassigned,
    [Display(Name = "Mobile Unverified")]
    Unverified_Mobile = 1,
    [Display(Name = "Email Unverified")]
    Unverified_Email = 2,
    [Display(Name = "Both")]
    Both = 3,
}

public class UnverifiedCustomersPayload
{
    public CustomersFilter Status { get; set; } = CustomersFilter.Unassigned;
}

The view part can be set as follow:视图部分可以设置如下:

@using WebApp.Models
@model UnverifiedCustomersPayload

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

The GetEnumSelectList method generates a SelectList object for an enum. GetEnumSelectList方法为枚举生成一个SelectList对象。

在此处输入图像描述

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

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