19
$("#bc [id$=_dropdownID]").change(function() {
    if (this.value == '2' || this.value == '3') {
        $("#bc .pnl").show();
    }
    else {
        $("#bc .pnl").hide();
    }

I have the following code in jQuery. Is there any way I can replace the hard coded constants 2 and 3 in the above code with a c# enum? Does jQuery support enums and if so how can this be achieved? Any suggestions welcome....

John Saunders
  • 157,405
  • 24
  • 229
  • 388
chugh97
  • 8,936
  • 24
  • 81
  • 132
  • 1
    See also http://stackoverflow.com/questions/287903/enums-in-javascript for lots of discussion. – goodeye Apr 29 '14 at 15:35

2 Answers2

49

You would have to duplicate the enum in JavaScript like so:

var myEnum = {
         OneValue: 2,
         AnotherValue: 3
};

then you can use it like this:

this.value === myEnum.OneValue || this.value === myEnum.AnotherValue;
sirrocco
  • 7,813
  • 3
  • 52
  • 80
0

Im using this way: If you got a enum anywhere in your c# project like :

   public enum MyEnum
     {
        One = 1,
        Two= 2
     }

(Supposing you wanna use it your entire project) In your Shared.Layout.cshtml file , at first line put its reference like bellow

@using MyProject.NameSpace.MyEnum

Inside Layout.cshml, at section put something like bellow

<script>
  const myEnum = { 
    One : @Convert.ToInt16(MyProject.NameSpace.MyEnum.One),
    Two : @Convert.ToInt16(MyProject.NameSpace.MyEnum.Two)
  }
</script>

In other places just compare something like

<script>
if(AnyValue == myEnum.One){
console.log(myEnum.One)
}
</script>
igorpcholkin
  • 880
  • 6
  • 15