简体   繁体   English

如何在Razor中获取枚举值

[英]How to get Enum value in Razor

I used datatables and I want to get Enum value for a specified int variable . 我用datatables ,我想Enum值指定INT variable

var client = $('td', row).eq(1).text().trim();

client is a number data type. 客户端是数字数据类型。

I tried this, but it is not working: 我试过了,但是没有用:

var x=@Enum.GetName(typeof(Client),client);

client does not exist in the current context 客户在当前上下文中不存在

Thanks in advance! 提前致谢!

@Enum.GetName(typeof(Client), client); is razor code which is parsed on the server before its sent to the view. 是在服务器发送到视图之前在服务器上解析的剃刀代码。 client is a javascript variable which does not exist at that point (its not in scope). client是当时不存在的JavaScript变量(不在范围内)。

On option would be to pass a collection of the enum names and values to the client, and assign it to a javascript array so it can be searched. On选项是将enum名称和值的集合传递给客户端,并将其分配给javascript数组,以便可以对其进行搜索。

For example, create a class to represent the names and values 例如,创建一个代表名称和值的类

public class EnumValues
{
    public int ID { get; set; }
    public string Name { get; set; }
}

and in your controller 并在您的控制器中

IEnumerable<EnumValues> clientValues = 
    from Client c in Enum.GetValues(typeof(Client))
    select new EnumValues
    {
        ID = (int)c,
        Name = c.ToString()
    };

and pass it to the view in a view model property, or using ViewBag 并将其传递给视图模型属性中的视图,或使用ViewBag

ViewBag.ClientValues = clientValues;

In the view, assign it to a javascript array, and create a function to return the name for a corresponding value 在视图中,将其分配给javascript数组,并创建一个函数以返回对应值的名称

var clients = @Html.Raw(Json.Encode(ViewBag.ClientValues));

function getClientName(value)
{
    for(var x = 0; x < clients.length; x++) {
        if (clients[i].ID == value) {
            return clients[i].Name;
        }
    }
    return null;
}

and use it as 并用作

var client = $('td', row).eq(1).text().trim();
var clientName = getClientName(client);

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

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