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

A portal focused on Operations and Support for Microsoft Azure Serverless services

FREE TRIAL

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.

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

    • August 7, 2017 at 9:18 am
      Permalink

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

    • August 7, 2017 at 9:41 am
      Permalink

      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.

    • Pingback:Extension to Razor HtmlHelper | Around computing

    • Pingback:The Morning Brew - Chris Alcock » The Morning Brew #2399

    • Pingback:Compelling Sunday – 19 Posts on Programming and QA

    • October 23, 2017 at 4:33 pm
      Permalink

      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?

    • December 10, 2019 at 8:37 am
      Permalink

      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

    Leave a Reply

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