2

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.

Mahesh

2 Answers 2

2

Suppose you have such enum with numeric values:

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:

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 arrColors is JS variable with both keys and values of your 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>
Sign up to request clarification or add additional context in comments.

13 Comments

Why not use JSON encoding of an enum? Surely there must be a way to turn an enum to JSON and then pass that to the page?
@Raynos interesting idea.. I prefer to stick with what I know but I now found this - the final result should be the same so the benefit is just doing it in more "elegant" way.. :)
@Shadow: Thanks for your reply. So how can i check the selected value is Yellow.
@mahesh - for this you don't need the C# enum at all, just such a line of code: if (selectedValue == "Yellow") { alert("you selected yellow"); }
@Shadow: i want to use that enum . Suppose if i change the enum value yellow to yyellow with the same value 1, then also it can be compare from javascript with out changing the javascript function
|
0

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

1 Comment

Yep but I believe he's after the value of each name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.