How to get Get a C# Enumeration in Javascript

Jishnu A P picture Jishnu A P · Mar 3, 2011 · Viewed 29.5k times · Source

I have a enum in my C# code and i want to get the same enum in javascript. Is there any way to fo this without hardcoding.

Thanks in advance

Answer

Sjoerd picture Sjoerd · Mar 15, 2013

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