DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Trending

  • Multi-Scale Feature Learning in CNN and U-Net Architectures
  • Top JavaScript/TypeScript Gen AI Frameworks for 2026
  • Mastering Fluent Bit: Beginners' Guide for Contributing to our CNCF Project Docs
  • GenAI Implementation Isn't Magic — It’s a Lifecycle
  1. DZone
  2. Coding
  3. Frameworks
  4. ASP.NET Core: Converting C# Enums to JavaScript

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.

By 
Gunnar Peipman user avatar
Gunnar Peipman
·
Aug. 31, 17 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
8.0K Views

Join the DZone community and get the full member experience.

Join For Free

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:

  • Converting C# Enums to JavaScript

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.

ASP.NET JavaScript ASP.NET Core

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

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook