Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ASP.NET Core: Converting C# Enums to JavaScript

DZone's Guide to

ASP.NET Core: Converting C# Enums to JavaScript

In this article, we pick up where we left off last time, and show you how you can convert C# enums to JavaScript while using ASP.NET Core.

· Web Dev Zone
Free Resource

Prove impact and reduce risk when rolling out new features. Optimizely Full Stack helps you experiment in any application.

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 the simple view component.

To get a better understanding of 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 large part, the code will be the same but there are some small differences in how reflection is used and how enums get to the page as JavaScript. On ASP.NET Core, I decided to use ViewComponent as it returns an instance of HtmlString.

JavaScriptEnum Attribute and Sample Enums

I begin again by defining the JavaScriptEnum attribute that marks our enums that 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 the 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 out view component is here, it is now time to try converting this to JavaScript.

Testing View Component

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

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

When a 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 APIs are a little different in ASP.NET Core than in classic ASP.NET, and on ASP.NET Core it's possible to use view components instead of HtmlHelper extension methods, the porting of enums to JavaScript code from classic ASP.NET to ASP.NET Core was actually simple and there was no need for big changes. The view component is actually a good choice, as it supports framework level dependency injection and is, therefore, open for more advanced scenarios.

With SDKs for all major client and server side platforms, you can experiment on any platform with Optimizely Full Stack.

Topics:
web dev ,enums ,javacript ,c#

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}