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!
Categories: ASP.NET JavaScript

View Comments (5)

  • simple. my 2 cents:
    * I would write is as extension to enum itself: `@AssetStatusEnum.ToJsString()`
    * And probably would go with camelCase notation

  • Thanks for feedback, Valdis! I considered also extension method for enum but abandoned the idea because extension methods for HtmlHelper are more popular and developers are more familiar with these. For noobies it is also the first object behind views they are going to check for helper methods.

  • By far the most succinct solution out there! Any tips on how to adapt this for place into an angularJS 1.6 controller as opposed to an HtmlHelper?

  • I'm getting error `` is a type, Which is not valid in the given context. What I'm missing I don't understand. Please help me.

    var PaymentGetewayEnum = @Html.EnumToString(PaymentGateways); ~ Error on Enum

Related Post