Skip to content Skip to sidebar Skip to footer

How To Use C# Enumeration Values In 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.

Solution 1:

Suppose you have such enum with numeric values:

publicenumColors
{
   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:

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

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

To use it, have such code for example:

<scripttype="text/javascript">functionSelectionChanged(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:

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

Solution 2:

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

Post a Comment for "How To Use C# Enumeration Values In Javascript"