ASP.NET Core: 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

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.

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

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

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

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.
Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    6 thoughts on “ASP.NET Core: Converting C# enums to JavaScript

    Leave a Reply

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