Extension to Razor HtmlHelper

How to export a C# enum:

public enum AssetStatusEnum
{
    Free,
    Reserved,
    Inactive,
    UnderMaintenance
}

to

    var assetStatusEnum = {"Free":0,"Reserved":1,"Inactive":2,"UnderMaintenance":3}

In implementing an extension method:

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));
    }
}

and using it like this:

    var assetStatusEnum = @(Html.EnumToString())

 

Converting C# enums to JavaScript | Gunnar Peipman – Programming Blog

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s