Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Converting Multiple C# Enums to JavaScript

DZone's Guide to

Converting Multiple C# Enums to JavaScript

In an earlier post we took a look at how you might convert a C# enum to one usable by JavaScript. In this follow-up post, we take a look at how to more easily convert multiple C# enums to JavaScript. Check it out!

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

My last solution for converting C# enums to JavaScript was simple but needed some additional work to support multiple enums better. After some playing with different approaches, I found a simple one that works okay for me. This blog post describes my simple solution that turns multiple C# enums into JavaScript with one shot.

NB! This post is like chapter two to my previous enums post Converting C# enums to JavaScript. The code in this and the current post is for ASP.NET MVC.

JavaScriptEnum Attribute

Solutions, where enums are used, don't usually use just one enum. Usually, there are many enums in server-side code. Some of these are also needed on the client-side, but not all of them. So, we need some way to find all enums in our code that we need also in JavaScript. The easiest way to mark some enums to be available in JavaScript is using a dummy attribute.


public class JavaScriptEnumAttribute : Attribute
{
}

We need this attribute only to detect enums that must be available in JavaScript.

Converting enum to JavaScript String

As a next thing we need a way to turn enum to JavaScript object. The code from previous enums post needs some refactoring – we need enum JavaScript as regular string and not as MvcHtmlString. Modified version of EnumToString() externsion method is here.


public static class HtmlEnumExtensions
{
    public static MvcHtmlString EnumToString<T>(this HtmlHelper helper)
    {
        return new MvcHtmlString(EnumToString<T>());
    }       private static string EnumToString<T>()
    {
        return EnumToString(typeof(T));
    }       private static string EnumToString(Type enumType)
    {
        var values = Enum.GetValues(enumType).Cast<int>();
        var enumDictionary = values.ToDictionary(value => Enum.GetName(enumType, value));           return JsonConvert.SerializeObject(enumDictionary);
    }
}

Now all methods that need enum’s JavaScript representation can get enum as JavaScript without any formatting. Just a plain JSON string with enum.

Converting Marked enums to JavaScript

To solve the problem of converting multiple enums to JavaScript with one shot we need a new extension method. This method detects all needed enums by looking for the JavaScriptEnum attribute and returns MvcHtmlString with the given JavaScript code.


public static MvcHtmlString JavaScriptEnums(this HtmlHelper helper)
{
    var query = from a in AppDomain.CurrentDomain.GetAssemblies()
                from t in a.GetTypes()
                from r in t.GetCustomAttributes<JavaScriptEnumAttribute>()
                where t.BaseType == typeof(Enum)
                select t;       var buffer = new StringBuilder(10000);

    foreach (var jsEnum in query)
    {
        buffer.Append("var ");
        buffer.Append(jsEnum.Name);
        buffer.Append(" = ");
        buffer.Append(EnumToString(jsEnum));
        buffer.Append("; \r\n");
    }       return new MvcHtmlString(buffer.ToString());
}

This method declares JavaScript variables with the same names as the enums that have the JavaScriptEnum attribute.

Using JavaScriptEnums Extension Method

To demonstrate how to use the JavaScriptEnums() extension method, let’s create a new ASP.NET MVC application with two enums.


[JavaScriptEnum]
public enum PaymentTypeEnum
{
    CreditCard,
    Check,
    Cash
}   [JavaScriptEnum]
public enum CustomerStatusEnum
{
    Regular,
    Gold,
    Platinum
}

Let’s call this method in the header of the layout page.


<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")       <script>
    @Html.JavaScriptEnums()
    </script>
</head>

And here is the result.


<script>
var PaymentTypeEnum = { "CreditCard": 0, "Check": 1, "Cash": 2 };
var CustomerStatusEnum = { "Regular": 0, "Gold": 1, "Platinum": 2 };
</script>

If it is possible, modify the code above and create a controller action that returns enums as JavaScript. Of course, then we get one additional call to the server.

Wrapping Up

After some playing with enums, we now have a decent solution to turn selected C# enums in our code to JavaScript with one shot. We used enum class methods and a little bit of reflection to work with enums. Marking enums with a marker attribute was perhaps not the best idea if we consider shared libraries, but, for simpler web applications, it works well. By using the HtmlHelper extension method for enums, we followed current ASP.NET MVC extending style and our code is easy to understand and follow for our fellow developers.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
enum ,extension ,c# ,javascript ,web dev

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}