ASP.NET Core Code Snippets
Filter by Set

ASP.NET Core Code Snippets

...see more

Let’s say that you have class Person and one of its properties is enum (in our case it’s enum Gender).

public enum Gender

Below you can see Razor Page with a simple HTML form. Please remember to add the using statement to the folder where is defined your enum type (in my case it’s @using SelectBindingEnum.Models).

<div class="form-group">
    <label asp-for="Person.Gender" class="control-label"></label>
    <select asp-for="Person.Gender" asp-items="Html.GetEnumSelectList<Gender>()" class="form-control"></select>
    <span asp-validation-for="Person.Gender" class="text-danger"></span>

As you can see above to binding enum values to HTML select tag you should use Tag Helper asp-items and HtmlHelper method GetEnumSelectList<T> where T is an enum type. This method generates a SelectList object for all enum values. Also, this method allows you to add Display attribute to your enum to change display text.

public enum Gender
   [Display(Name = "None")]

If you would add this attribute, you will see the following values in HTML select tag: None, Male and Female.

...see more

Some properties of model classes come as enums and we want to show Enum values in a select list. Sometimes we want enum element names but sometimes we want to use custom names or even translations.

Let’s define the enum and make it use DisplayAttribute and resource file.

public enum CustomerTypeEnum
    [Display(Name = "Companies")]

    [Display(Name = "PublicSector", ResourceType = typeof(Resources.Common))]

There are three different cases together now:

  1. Enum member with just a name
  2. Enum member with Display attribute and static name
  3. Enum member with Display attribute and resource file

Important thing: set resource modifier to Public.

Now use the Html.GetEnumSelectList() extension method to fill the select list with enum members. Notice the first empty selection (Select type …) as the only member of the select list.

<div class="form-group">
    <label asp-for="Type" class="control-label"></label>
    <select asp-for="Type" 
        option>Select type ...option>
    <span asp-validation-for="Type" class="text-danger"><span>

When we run the application we can see that the select list is filled with enum members and ASP.NET Core respects DisplayAttribute with static name and resource files.

If you don’t have control over enum (enum is defined in already built assembly) then you can’t apply Display attribute to enum and you need some other solution to get values you need.

Wrapping up

ASP.NET Core has built-in Html.GetEnumSelectList() method we can use to turn enum members to select list items. The method is intelligent enough to support the Display attribute and therefore we can use custom names for enum members and even translations from resource files.

...see more

Here’s my claims transformation that adds roles to user identity.

public class AddRolesClaimsTransformation : IClaimsTransformation
    private readonly IUserService _userService;
    public AddRolesClaimsTransformation(IUserService userService)
        _userService = userService;
    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        // Clone current identity
        var clone = principal.Clone();
        var newIdentity = (ClaimsIdentity)clone.Identity;
        // Support AD and local accounts
        var nameId = principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier ||
                                                          c.Type == ClaimTypes.Name);
        if (nameId == null)
            return principal;
        // Get user from database
        var user = await _userService.GetByUserName(nameId.Value);
        if (user == null)
            return principal;
        // Add role claims to cloned identity
        foreach(var role in user.Roles)
            var claim = new Claim(newIdentity.RoleClaimType, role.Name);
        return clone;
...see more

The following sample will return JSON with a 200 OK status code (it's an Ok type of ObjectResult)

public IActionResult GetAsJson()
   return new OkObjectResult(new Catagory { Id = 1234, Name = "Articles" });

The following code uses the Produces() attribute (which is a ResultFilter) with contentType = application/json

public Student GetWithProduces()
    return new Catagory { Id = 1234, Name = "Articles" };

Return JSON with a 400 error code with a message

public IActionResult ErrorJSON()
    return new JsonResult(new { message = "The Error Messages" })
StatusCode = StatusCodes.Status400BadRequest // Status code here 
...see more

How to return JSON in camelCase?

Configure in Startup.cs

First of all, add this dependency:

using System.Text.Json;

Then add this in ConfigureServices():

services.AddJsonOptions(options =>
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;

Change JsonSerializer options

Supply JsonSerializer.Serialize() with the optional JsonSerializerOptions object and override the casing:

string jsonString = JsonSerializer.Serialize(m, new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
Add to Set
  • .NET 6.0 Migration
  • 5 Best websites to read books online free with no downloads
  • 5 surprising things that men find unattractive
  • 5 Ways To Take Control of Overthinking
  • 6 simple methods for a more productive workday
  • 6 Ways To Stop Stressing About Things You Can't Control
  • Add React to ASP.NET Core
  • Adding reCAPTCHA to a .NET Core Web Site
  • Admin Accounts
  • Adobe Acrobat
  • Afraid of the new job? 7 positive tips against negative feelings
  • Agile
  • AI
  • AKS and Kubernetes Commands (kubectl)
  • API Lifecycle Management
  • Application Insights
  • arc42
  • Architectures
  • Article Writing Tools
  • ASP.NET Core Code Snippets
  • ASP.NET Core Performance Best Practices
  • ASP.NET Core Razor Pages
  • ASP.NET: Razor Syntax Cheat Sheet
  • Atlassian
  • Azure
  • Azure API Management
  • Azure App Registration
  • Azure Application Gateway
  • Azure Arc
  • Azure Arc Commands
  • Azure Architectures
  • Azure Bastion
  • Azure Bicep
  • Azure CLI Commands
  • Azure Cloud Products
  • Azure Cognitive Services
  • Azure Container Apps
  • Azure Cosmos DB
  • Azure Cosmos DB Commands
  • Azure Costs
  • Azure Daily
  • Azure Daily 2022
  • Azure Daily 2023
  • Azure Data Factory
  • Azure Database for MySQL
  • Azure Database for PostgreSQL
  • Azure Databricks
  • Azure Diagram Samples
  • Azure Durable Functions
  • Azure Firewall
  • Azure Functions
  • Azure Kubernetes Service (AKS)
  • Azure Landing Zone
  • Azure Log Analytics
  • Azure Logic Apps
  • Azure Maps
  • Azure Monitor
  • Azure News
  • Azure PowerShell Cmdlets
  • Azure PowerShell Login
  • Azure Private Link
  • Azure Purview
  • Azure Redis Cache
  • Azure Security Groups
  • Azure Sentinel
  • Azure Service Bus
  • Azure Service Bus Questions (FAQ)
  • Azure Services Abstract
  • Azure SQL
  • Azure Storage Account
  • Azure Tips and Tricks
  • Backlog Items
  • BASH Programming
  • Best LinkedIn Tips (Demo Test)
  • Best Practices for RESTful API
  • Bing Maps
  • Birthday Gift Ideas for Wife
  • Birthday Poems
  • Black Backgrounds and Wallpapers
  • Bootstrap Templates
  • Brave New World
  • Break Out of a JavaScript Loop
  • Brian Tracy Quotes
  • Build Websites Resources
  • C# Code Samples
  • C# Design Patterns
  • C# Development Issues
  • C# Programming Guide
  • Caching
  • Caching Patterns
  • Camping Trip Checklist
  • Canary Deployment
  • Careers of the Future You Should Know About
  • Cheap Vacation Ideas
  • Cloud Computing
  • Cloud Migration Methods
  • Cloud Native Applications
  • Cloud Service Models
  • Cloudflare
  • Code Snippets
  • Collection in JavaScript
  • Compelling Reasons Why Money Can’t Buy Happiness
  • Conditional Access
  • Configurations for Application Insights
  • Const in JavaScript
  • Create a Routine
  • Create sitemap.xml in ASP.NET Core
  • Creative Writing: Exercises for creative texts
  • CSS Selectors Cheat Sheet
  • Cultivate a Growth Mindset
  • Cultivate a Growth Mindset by Stealing From Silicon Valley
  • Custom Script Extension for Windows
  • Daily Scrum (Meeting)
  • Dalai Lama Quotes
  • Data Generators
  • DataGridView
  • Decision Trees
  • Deployments in Azure
  • Dev Box
  • Develop ASP.NET Core with React
  • Development Flows
  • Docker
  • Don’t End a Meeting Without Doing These 3 Things
  • Drink More Water: This is How it Works
  • Dropdown Filter
  • Earl Nightingale Quotes
  • Easy Steps Towards Energy Efficiency
  • Elon Musk
  • Elon Musk Companies
  • Employment
  • English
  • Entity Framework Core: Syntax and Commands
  • Escape Double Quotes in C#
  • Escaping characters in C#
  • Executing Raw SQL Queries using Entity Framework Core
  • Factors to Consider While Selecting the Best Earthmoving System
  • Feng Shui 101: How to Harmonize Your Home in the New Year
  • Flying Machines
  • Foods against cravings
  • Foods that cool you from the inside
  • Four Misconceptions About Drinking
  • Fox News
  • Free APIs
  • Funny Life Quotes
  • Generate Faces
  • Generate Random Numbers in C#
  • Genius Money Hacks for Massive Savings
  • Git
  • Git Cheat Sheet
  • Git for Beginners
  • Git Fork
  • GitHub
  • GitHub Concepts
  • Green Careers Set to Grow in the Next Decade
  • Habits Of Highly Stressed People and how to avoid them
  • Happy Birthday Wishes & Quotes
  • Helm Overview
  • How to Clean Floors – Tips & Tricks
  • How to invest during the 2021 pandemic
  • How To Make Money From Real Estate
  • How To Stop Drinking Coffee
  • HTTP Status Code
  • Image for Websites
  • Inspirational Quotes
  • Iqra Technology, IT Services provider Company
  • JavaScript
  • JavaScript Scope
  • JavaScript Snippets
  • JavaScript Var, Let, and Const
  • Jobs Of 2050
  • jQuery
  • jQuery plugins
  • JSON (JavaScript Object Notation)
  • JSON for Linking Data (JSON-LD)
  • Json to C# Converters
  • JSON Tree Viewer JavaScript Plugin
  • JSX (ReactJS)
  • Karen Lamb Quotes
  • Kubernetes Objects
  • Kubernetes Tools
  • Kusto Query Language
  • Lack of time at work? 5 simple tricks to help you avoid stress
  • Lambda (C#)
  • Last Minute Travel Tips
  • Last-Minute-Reisetipps
  • Latest Robotics
  • Leadership
  • Let in JavaScript
  • List Of Hobbies And Interests
  • Logitech BRIO Webcam
  • Management
  • Mark Twain Quotes
  • Markdown
  • Meet Sophia
  • Message-Oriented Architecture
  • Microservices
  • Microsoft Authenticator App
  • Microsoft Power Automate
  • Microsoft SQL Server
  • Microsoft Teams
  • Mobile UI Frameworks
  • Motivation
  • Multilingual Applications
  • NBC News
  • NuGet
  • OAuth Authentication Flows
  • Objectives and Key Results (OKR)
  • Objectives and Key Results (OKR) Samples
  • OKR Software
  • Online JSON Viewer and Parser
  • Outlook Automation
  • PCMag
  • Phases of any relationship
  • Playwright
  • Popular cars per decade
  • Popular Quotes
  • PowerShell
  • PowerShell Array Guide
  • PowerShell Cmdlets
  • PowerShell Coding Samples
  • PowerToys
  • Prism
  • Pros & Cons Of Alternative Energy
  • Quill Rich Text Editor
  • Quotes
  • RACI Matrix
  • Razor Syntax
  • Reasons why singletasking is better than multitasking
  • Regular Expression (RegEx)
  • Reorder List in JavaScript
  • Resize Images in C#
  • Response Caching in ASP.NET Core
  • RESTful APIs
  • Rich Text Editors
  • Rob Siltanen Quotes
  • Robots
  • Run sudo commands
  • Salesforce Offshore Support Services Providers
  • Sample Data
  • Save Money On Food
  • Score with authenticity in the job interview
  • Scrum
  • Scrum Meetings
  • Security
  • Semantic Versioning
  • Serialization using Thread Synchronization
  • Service Worker
  • Snipps
  • Speak and Presentation
  • SQL Functions
  • SQL References
  • SQL Server Full-Text Search
  • Successful
  • Surface Lineup 2021
  • Surface Lineup 2021 Videos
  • SVG Online Editors
  • Team Manifesto
  • Technologies
  • Technology Abbreviations
  • Technology Glossary
  • TechSpot
  • That is why you should drink cucumber water every day
  • The Cache Tag Helper in ASP.NET Core
  • The Verge
  • Theodore Roosevelt Quotes
  • These 7 things make you unattractive
  • Things Successful People Do That Others Don’t
  • Things to Consider for a Great Birthday Party
  • Things to Consider When Designing A Website
  • Thoughts
  • TinyMCE Image Options
  • TinyMCE Toolbar Options
  • Tips for a Joyful Life
  • Tips for fewer emails at work
  • Tips for Making Better Decisions
  • Tips for Managing the Stress of Working at Home
  • Tips for Writing that Great Blog Post
  • Tips On Giving Flowers As Gifts
  • Tips you will listen better
  • Top Fitness Tips
  • Top Healthy Tips
  • Top Money Tips
  • Top Ten Jobs
  • Track Authenticated Users in Application Insights
  • Unicode Characters
  • Var in JavaScript
  • Visual Studio 2022
  • Vital everyday work: tips for healthy work
  • Walking barefoot strengthens your immune system
  • Walt Disney Quotes
  • Ways for Kids to Make Money
  • Web Design Trends & Ideas
  • Web Icons
  • Web Scraping
  • Webhooks
  • Website Feature Development
  • What are my options for investing money?
  • What happens when you drink water in the morning
  • What Is Stressful About Working at Home
  • What To Eat For Lunch
  • Windows
  • Windows 11 Top Features You Should Know
  • Winston Churchill Quotes
  • XPath
  • You'll burn out your team with these 5 leadership mistakes
  • ZDNet