在javascript中,如何读取enum值?

时间:2023-01-26 14:28:51

I have created json variable called "grouptypejson" as mentioned below:-

我创建了一个名为“grouptypejson”的json变量,如下所述:-

var grouptypejson = {
    "opt": [
             {
                "n": "@SampleResource.GENERIC",
                "v": 0
             },
             {
                "n": "@SampleResource.DEPARTMENT",
                "v": 1
             }
           ]
}; 

The above json variable is defined globally in cshtml page under javascript body.

上面的json变量是在javascript主体下的cshtml页面中全局定义的。

I am using hardcoded value i.e. "v":0 & "v":1

我使用硬编码的值。“v”:0和“v”:1

Instead of using hardcoded value, I want to get the number via enum which is defined under models namespace i.e. mentioned below:-

我不想使用硬编码的值,我想通过在模型命名空间中定义的枚举数,例如:-

namespace My.Sample.Models.Enums
{
    public enum FilterEnum
    {
        Generic = 0,
        Department,
        All
    }
}

I want to read the value using the above enum and store the same at hard coded place

我希望使用上面的枚举读取这个值,并在硬编码的地方存储相同的值。

i.e. "v":0 & "v":1

即。“v”:0和“v”:1

I don't know how to get the enum value as integer and store at "v".

我不知道如何将enum值设为整数并存储在“v”。

I tried using the following mentioned below but the result was Generic & Department respectively. Replaced 0 & 1 with the below string at the above json variable.

我尝试使用下面提到的方法,但是结果是通用的和部门的。在上面的json变量处用下面的字符串替换0和1。

 "v":"@FilterEnum.GENERIC" & "v":"@FilterEnum.DEPARTMENT"

Please guide me how to do the same, I am including the enum namespace in my html page.

请指导我如何做同样的事情,我在html页面中包含enum名称空间。

Please correct me if i have written anything wrong. I am beginner & learner.

如果我写错了,请纠正我。我是初学者和学习者。

Thanks in advance.

提前谢谢。

1 个解决方案

#1


2  

You can cast enum to int:

可以将enum转换为int:

var grouptypejson = {
    "opt": [
             {
                "n": "@SampleResource.GENERIC",
                "v": @((int)SampleResource.GENERIC)
             },
             {
                "n": "@SampleResource.DEPARTMENT",
                "v": @((int)SampleResource.DEPARTMENT)
             }
           ]
}; 

#1


2  

You can cast enum to int:

可以将enum转换为int:

var grouptypejson = {
    "opt": [
             {
                "n": "@SampleResource.GENERIC",
                "v": @((int)SampleResource.GENERIC)
             },
             {
                "n": "@SampleResource.DEPARTMENT",
                "v": @((int)SampleResource.DEPARTMENT)
             }
           ]
};