Friday, 23 March 2012

Accessing C# Enumerations on the client side

So you spend all of that time carving out beautifully detailed Enums in your C# code but when you come to write your JavaScript code find yourself rewriting them all from scratch. Wouldn't it be nice if you could easily have them available in the client side scripts without too much effort... Well here is a solution that just does that:

First of all create an extension method for Enums which converts the Enum into a JSON string:


///
/// Serialize an enum's values to a JSON string returning a snippet of JavaScript
/// code that can be used to access the enum's values on the client side with out
/// duplicating the enum in your JavaScript code.
///

/// Enumerated type to serialize to JSON.
/// {"enum_value_1": "enum_value_1", "enum_value_2": "enum_value_2", ...};
public static string ToJson(this Enum en)
{
StringBuilder json = new StringBuilder();
json.Append("{");

List enumFields = new List();

Type type = en.GetType();

foreach (var value in Enum.GetValues(type))
{
enumFields.Add("\"" + value.ToString() + "\": \"" + value.ToString() + "\"");
}

json.Append(string.Join(", ", enumFields.ToArray()));
json.Append("}");

return json.ToString();
}


Then whenever you are creating a page on the server side just write this Enum into the JavaScript using:


Enum.ToJson()


Prototyping the result to an object you can access on the client side and voila! You have made your server side Enum's available on the client side!