33

I have an enum in my C# code and I want to get the same enum in javascript.

Is there any way to do this without hardcoding?

1

7 Answers 7

42

You can serialize all enum values to JSON:

private void ExportEnum<T>()
{
    var type = typeof(T);
    var values = Enum.GetValues(type).Cast<T>();
    var dict = values.ToDictionary(e => e.ToString(), e => Convert.ToInt32(e));
    var json = new JavaScriptSerializer().Serialize(dict);
    var script = string.Format("{0}={1};", type.Name, json);
    System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "CloseLightbox", script, true);
}

ExportEnum<MyEnum>();

This registers a script like:

MyEnum={"Red":1,"Green":2,"Blue":3};
Sign up to request clarification or add additional context in comments.

1 Comment

I realize this is a nearly three-year-old answer, but nonetheless, major props for what I think is a really elegant solution to this problem.
7

If you want it as viewmodel -> view -> JS

Requires:

using Newtonsoft.Json;
using System;

Viewmodel:

// viewmodel property:
 public string MyEumJson
        {
            get
            {
                return JsonConvert.SerializeObject(Enum.GetValues(typeof(MyEum)), new Newtonsoft.Json.Converters.StringEnumConverter());
            }
        }

Then in your .cshtml:

@* View *@

<script>
    var myEnumInJS = '@Html.Raw(Model.MyEumJson)';
</script>

this will be evaluated as

enter image description here

2 Comments

and how to user it
@BasheerAL-MOMANI I had the same question, try like this: var text = myEnumInJS[1]'
5

Yes you can do it like this, i did it like this:

    var OrderStateId = parseInt(stateVal);

    if (OrderStateId === @((int)OrderStates.Approved)) {
        // 5 is the Approved state
        if (OrderOption === "Quote") {
        $('#quoteDiv').css('display', 'block');
    } 

Comments

1

You can convert it to a list and then serialise it to JSON, for example:

// In the code-behind
private void _Default_Load(object sender, EventArgs e)
{
    var objects = GetObjects();

    var serialiser = new JavaScriptSerializer();
    this.MyHiddenField.Value = serialiser.Serialize(objects);
}

// Example enumerable
static IEnumerable<MyClass> GetObjects()
{
    for (int i = 0; i < 10; i++)
    {
        yield return new MyClass();
    }
}

The above requires .Net 3.5 and a reference to the System.Web.Extensions assembly (for the use of JavaScriptSerializer, however alternative JSON serialisation libraries exist for .Net.

In your javascript code you should use a JSON serialisation library (such as json2) to deserialise your list:

var mylist = JSON.parse($("#MyHiddenField").val());
for (var i in mylist)
{
     var item = mylist[i];
}

Update: Agg, I promise to actually read the question next time - enumeration, not enumerable!

Comments

1

For Razor

Works perfectly for Razor like this

var Enumerators = {
   System: {
           @{
               <text>DayOfWeek: JSON.parse('@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Enum.GetValues(typeof(DayOfWeek)), new Newtonsoft.Json.Converters.StringEnumConverter()))')</text>
           }
    }
}

This would give result like this in javaScript
Enumerators.System.DayOfWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

Please let me know if there is a mistake or not accordingly fitting to the required need, Thank You

For C# Server Side

Please see the following answer that might be useful

https://stackoverflow.com/a/29184357/6737444

Comments

0

Here is the post that answered your question:

JSON serialization of enum as string

Comments

-2

I found a good solution here

http://fairwaytech.com/2014/03/making-c-enums-available-within-javascript/

The only problem I have is that it doesn't carry the Description attributes. If you don't use/need descriptions then it is perfect.

This provides you with access on the client side, like so:

var Enums = { 
    phoneType: {phone:1,fax:2,voiceMail:3,cell:4,},
    addressType: {mailing:1,physical:2,} 
    };

Comments

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.