ASP.NET Core: Converting C# enums to JavaScript

In my previous posts about enums I covered how to convert C# enums to JavaScript on classic ASP.NET MVC. This blog post introduces how to do it on ASP.NET Core using simple view component.

To get better understanding about my previous work on getting C# enums to JavaScript on classic ASP.NET MVC I suggest to read my following blog posts:

This post takes the latter one as a base and ports it to ASP.NET Core. In big part the code will be the same but there are some small differences in how reflection is used and how enums get to page as JavaScript. On ASP.NET Core I decided to use ViewComponent that returns instance of HtmlString.

JavaScriptEnum attribute and sample enums

I begin again by defining JavaScriptEnum attribute that marks our enums we want to get to JavaScript. I also define two simple enums for testing.

public class JavaScriptEnumAttribute : Attribute
{
}

[JavaScriptEnum]
public enum PaymentTypeEnum
{
    CreditCard,
    Check,
    Cash
}

[JavaScriptEnum]
public enum CustomerStatusEnum
{
    Regular,
    Gold,
    Platinum
}

Now let’s get to real business.

Defining view component

I decided to go with view component that returns enums in JavaScript as HtmlString This view component doesn’t have any view as view for this simple output would be overkill.

public class EnumsToJavaScriptViewComponent : ViewComponent
{
    public Task<HtmlString> InvokeAsync()
    {           
        var query = from a in GetReferencingAssemblies()
                    from t in a.GetTypes()
                    from r in t.GetTypeInfo().GetCustomAttributes<JavaScriptEnumAttribute>()
                    where t.GetTypeInfo().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 Task.FromResult(new HtmlString(buffer.ToString()));
    }

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

    private static IEnumerable<Assembly> GetReferencingAssemblies()
    {
        var assemblies = new List<Assembly>();
        var dependencies = DependencyContext.Default.RuntimeLibraries;

        foreach (var library in dependencies)
        {
            try
            {
                var assembly = Assembly.Load(new AssemblyName(library.Name));
                assemblies.Add(assembly);
            }
            catch (FileNotFoundException)
            { }
        }
        return assemblies;
    }
}

As view component is here it is now time to try it.

Testing view component

My decision was to include view component to layout page of web application.

<script>
@await Component.InvokeAsync("EnumsToJavaScript")
</script>

When web application is run the script block above looks like this.

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

Now the enums marked for JavaScript are available in JavaScript.

Wrapping up

Although reflection API-s are little different in ASP.NET Core and classic ASP.NET and on ASP.NET Core it’s possible to use view components instead of HtmlHelper extension methods, porting of enums to JavaScript code from classic ASP.NET to ASP.NET Core was actually simple and there were no need for big changes. View component is actually good choice as it supports framework level dependency injection and is therefore open for more advanced scenarios.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    Leave a Reply

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