Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a C# enumeration in Javascript

I have a enum in my C# code and i want to get names from enum in my jQuery validate rules.

Enum:

public enum EnumItemField
{
    Zero = 0,
    One = 1,
    Two = 2,
    Three = 3,
    Four = 4,
    Five = 5,
} 

Validate:

function updateFieldStatus() {
}

$(document).ready(function () {
$("#IntegrationService").validate({
    rules: {
        //Set range of Start
        "config.EnumFormat[Zero].Start": {
            required: true,
            digits: true,
            range: [1, 200]
        },
        "config.EnumFormat[One].Start": {
            required: true,
            digits: true,        
            range: [1, 200]
        },
    },
    submitHandler: function () {
        MsgBoxService.show({
            //setId: "saveload",
            //objectId: "asrun"
        });
    },
}); 

This really works, but I want make something like this:

"config.EnumFormat[" + item + "].Start": {
    required: true,
    digits: true,
    range: [1, 200]
}

In C# I can get names in this way:

foreach (var item in Enum.GetNames(typeof(EnumItemField)))

How can I make it in javascript? Thanks for advice!

like image 377
str_str Avatar asked Dec 29 '15 14:12

str_str


1 Answers

You can make the same thing as a JavaScript Object.

EnumItemField = {
    "Zero": 0,
    "One": 1,
    "Two": 2,
    "Three": 3,
    "Four": 4,
    "Five": 5
}

Please don't forget to remove the last , comma.

You can use the values like:

EnumItemField.Zero     // 0
EnumItemField["Zero"]  // 0

Iteration? No problem:

for (var item in EnumItemField) {
  item;                // Zero
  EnumItemField[item]; // 0
}
like image 191
Praveen Kumar Purushothaman Avatar answered Sep 23 '22 04:09

Praveen Kumar Purushothaman