Converting C# enums to JavaScript

In one of my project I need some enums defined in C# to able also for JavaScript code. After some quick research in internet I came out with simple and easy extension method to convert C# enums to JavaScript. Here it is.

Let’s get started with example enum and suppose we want to be able to use it also in JavaScript.


public enum AssetStatusEnum
{
    Free,
    Reserved,
    Inactive,
    UnderMaintenance
}

To make enum available in JavaScript we have to convert it to JSON. As Enum.GetValues() returns Array and Array doesn’t have LINQ extensions available we have to cast array to IEnumerable<int> before converting it to dictionary.We need dictionary because JSON converter that comes with popular NewtonSoft JSON package will serialize it to JavaScript array.

Here is the extension method for HtmlHelper and this method returns enum as JavaScript object string.


public static class HtmlEnumExtensions
{
    public static MvcHtmlString EnumToString<T>(this HtmlHelper helper)
    {
        var values = Enum.GetValues(typeof(T)).Cast<int>();
        var enumDictionary = values.ToDictionary(value => Enum.GetName(typeof(T), value));

        return new MvcHtmlString(JsonConvert.SerializeObject(enumDictionary));
    }
}

This is how we call our extension method in views.


<script>
    var assetStatusEnum = @(Html.EnumToString<AssetStatusEnum>())
</script>

And this is the result of converting our AssetStatusEnum to JavaScript.


<script>
    var assetStatusEnum = {"Free":0,"Reserved":1,"Inactive":2,"UnderMaintenance":3}
</script>

Our extension method has the following benefits:

  • simple and easy to debug code,
  • no more manually duplicated enums in JavaScript anymore,
  • enums in JavaScript are always up to date.


See also

5 thoughts on “Converting C# enums to JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *