如何在 JavaScript 中使用 C# 枚举值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5537271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:33:06  来源:igfitidea点击:

How to use C# enumeration values in JavaScript

c#javascriptasp.netenums

提问by Mahesh KP

I have got an enumeration in C# ie something like Category.cs.
In a dropdownlist we are binding values.
So if the user selects some specific value in dropdown it will hide one div.
So i want to get the enumeration value in javascript ie want to compare the enumeration value with one selected value in javascript.

我在 C# 中得到了一个枚举,即类似于 Category.cs 的东西。
在下拉列表中,我们正在绑定值。
因此,如果用户在下拉列表中选择某个特定值,它将隐藏一个 div。
所以我想在 javascript 中获取枚举值,即想将枚举值与 javascript 中的一个选定值进行比较。

Mahesh

马赫什

采纳答案by Shadow Wizard is Ear For You

Suppose you have such enumwith numeric values:

假设你有这样enum的数值:

public enum Colors
{
   Yellow = 1,
   Red,
   Blue,
   Green,
   Purple
}

First of all, in the code behind (Page_Load event) register JavaScript code that will build client side structure that hold the same data:

首先,在后面的代码(Page_Load 事件)中注册将构建保存相同数据的客户端结构的 JavaScript 代码:

string strJS = string.Format("var arrColors = {{{0}}}; ",
    string.Join(", ", Enum.GetNames(typeof(Colors)).ToList().ConvertAll(key =>
{
    return string.Format("{0}: {1}", key, (int)((Colors)Enum.Parse(typeof(Colors), key)));
}).ToArray()));
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "enum", strJS, true);

Now arrColorsis JS variable with both keys and values of your enum.

现在arrColors是带有键和值的 JS 变量enum

To use it, have such code for example:

要使用它,例如有这样的代码:

<script type="text/javascript">
   function SelectionChanged(oDDL) {
      var selectedValue = oDDL.value;
      var enumValue = arrColors[selectedValue] || "N/A";
      alert("enum value for '" + selectedValue + "' is: " + enumValue);
   }
</script>

And the drop down should look like this:

下拉菜单应如下所示:

<select onchange="SelectionChanged(this);">
    <option>Select..</option>
    <option value="Yellow">Yellow</option>
    <option value="Green">Green</option>
</select>

回答by Bogdan Verbenets

System.Enum.GetNames(typeof(yourenumerationtype))- returns an array of strings, which represents enumeration items' names

System.Enum.GetNames(typeof(yourenumerationtype))- 返回一个字符串数组,表示枚举项的名称