masaj salonu masaj salonları
Home » Advertising » Converting C# Enums to JavaScript

Converting C# Enums to JavaScript

Let’s get started with an example enum and suppose we want to be able to also use it with 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 an array to IEnumerableint before converting it to a dictionary. We need a dictionary because the JSON converter that comes with the popular NewtonSoft JSON package will serialize it to a 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 EnumToStringT(this HtmlHelper helper)
    {
        var values = Enum.GetValues(typeof(T)).Castint();
        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.EnumToStringAssetStatusEnum())
/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.
  • Enums in JavaScript are always up to date.

Leave a Reply

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

*
*

cover letter