How to get Get a C# Enumeration in Javascript

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};

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


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');
    }