如何使用C#枚举值在JavaScript中 [英] How to use C# enumeration values in JavaScript
问题描述
我有在C#即像Category.cs枚举。结果
在DropDownList中我们绑定值。结果
因此,如果用户在下拉列表中选择一些特定的值时,它会隐藏一个DIV。结果
所以我想在javascript中即要枚举值在JavaScript中一个选定的值进行比较的枚举值。
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.
马赫什
推荐答案
假设你有这样的枚举
与数值:
Suppose you have such enum
with numeric values:
public enum Colors
{
Yellow = 1,
Red,
Blue,
Green,
Purple
}
首先,在后面的code(Page_Load事件)的JavaScript注册code,将建立持有相同的数据客户端结构:
First of all, in the code behind (Page_Load event) register JavaScript code that will build client side structure that hold the same data:
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);
现在 arrColors
是与键和值JS变量的枚举
。
Now arrColors
is JS variable with both keys and values of your enum
.
要使用它,有这样code,例如:
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>
和下拉应该是这样的:
<select onchange="SelectionChanged(this);">
<option>Select..</option>
<option value="Yellow">Yellow</option>
<option value="Green">Green</option>
</select>
这篇关于如何使用C#枚举值在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!