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