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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Unlocking AI Coding Assistants Part 3: Generating Diagrams, Open API Specs, And Test Data
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  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
7.7K 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, DZone MVB. 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
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!