In my last blog post, I discussed range inputs. This time, we’ll examine a tag helper that adds support for the HTML element of datalist.
In this short post, I’ll explain what a datalist is and why you may want to consider using it in your ASP.NET Core applications. Finally, we’ll implement a set of tag helpers to make using the datalist element more straightforward with your ASP.NET Core MVC and Razor Page applications.
What is datalist?
True to its name, the datalist element allows web developers to create a list of options that are permissible or recommended for form input elements. This allows users to choose from a predefined list the application developer has curated.
Let’s look at a quick HTML example pulled from the MDN web docs.
The ice-cream-choice field will use the datalist options and provide users with a dropdown of potential options but still allow users to type their choices using freeform text.
The list attribute supports multiple input types, including text, date, range, and color. While the datalist is supported in most browsers, Firefox partially supports the input field and does not work with the types date, time, range, and color.
Providing a datalist can guide your users to common answers for otherwise fuzzy fields. The element might be helpful in surveys or support forms.
How do we use it in ASP.NET Core MVC and Razor Pages?
Datalist TagHelper for MVC and Razor Pages
Let’s start with our end goal of using a datalist in our Razor views. We’ll look at a Razor Pages example where we’ll see the HTML and C# Page Model.
We’ll reuse the SelectListItem class commonly used by the select element. There’s no reason to reinvent the wheel here. Next, let’s update our view.
That’s it! We now have an input field backed by our new datalist. Let’s see what the output HTML looks like.
The tag helpers are designed to look for asp-items on a datalist element and an asp-list attribute on any input field. Let’s see how these two tag helpers are implemented.
This straightforward implementation could easily be modified to accommodate your needs.
The most crucial implementation detail is the ModelExpression, which allows us to get both the metadata of our property and the value of the property. It’s an awesome part of the tag helper API.
Conclusion
The datalist element is an HTML-native feature that provides completion on several input types. With a few simple tag helpers, we can derive the datalist options we need to power any input, thus reducing the work required to keep the UI and application data models in sync. Please try this and let me know if you found it helpful.
As always, thanks for reading, and cheers.
Photo by 