How to get Get a C# Enumeration in Javascript

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?

13 thoughts on “How to get Get a C# Enumeration in Javascript”

  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!

    Reply
  2. 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};
    
    Reply
  3. 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

    Reply
  4. 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');
        } 
    
    Reply
  5. 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

    Reply

Leave a Comment