Uncategorized

Selectable Enum Dropdown List Using TagHelpers

This post is going to look into how populate a dropdown list with the contents of an enum using a TagHelper and an HTML Helper.

In case you aren’t familiar with TagHelpers, TLDR:

TagHelpers use server-side code to render HTML concisely and is readable for those not familiar with Razor markup.

If you want to learn more, checkout the docs here.

Alright, let’s dive in with our setup!

Enum:

public enum DogName
{
       Fido,
       Buddy,
       Bear
}

Model:

public class Dog
{
      public DogName DogName{ get; set; }
}

Make sure both the class and property are public.

View:

In the beginning of your view, be sure to bind the Model:

@model RescueShare.Models.Dog

Then, using our <select> TagHelper in our Razor View to create the actual dropdown:

<select asp-for="DogName"
asp-items="Html.GetEnumSelectList<DogName>()">
</select>

The asp-for attribute binds the values to the DogName property. Then, asp-items populuates the dropdown with values from our DogName enum using our GetEnumSelectList HTML Helper.

Here are the major benefits for using a TagHelper in this scenario:

  1. Ability to access server-side data
  2. Concise and easy to read
  3. Works with Intellisense

And that’s it! We have gone through how to successfully bind a <select> TagHelper to an enum in a Razor View using an HTML Helper for an ASP.NET Core MVC app!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s