Home » Advertising » Converting Multiple C# Enums to JavaScript

Converting Multiple C# Enums to JavaScript

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 EnumToStringT(this HtmlHelper helper)
    {
        return new MvcHtmlString(EnumToStringT());
    }       private static string EnumToStringT()
    {
        return EnumToString(typeof(T));
    }       private static string EnumToString(Type enumType)
    {
        var values = Enum.GetValues(enumType).Castint();
        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.GetCustomAttributesJavaScriptEnumAttribute()
                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("; rn");
    }       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.

Leave a Reply

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

*
*

cover letter