Create AutoPostBack tag helper in ASP.NET Core

In one of my
past
articles I explained how autopostback can be implemented in ASP.NET Core. If
you find yourself using autopostback at many places, you can create a custom tag
helper that does the job for you. To that end this short post explains how that can
be done.
This post doesn't discuss the basics of custom tag helpers. If you are not
familiar with creating your own tag helpers read
this article
go get some understanding.
Have a look at the following custom tag helper named AutoPostBackTagHelper
that automatically submits a form when the selection in the dropdown changes.
[HtmlTargetElement("select", Attributes = "autopostback")]
public class AutoPostBackTagHelper : TagHelper
{
public bool autopostback { get; set; }
public override void Process(TagHelperContext
context, TagHelperOutput output)
{
if (AutoPostBack)
{
output.Attributes.SetAttribute("onchange",
"this.form.submit();");
}
}
}
The AutoPostBackTagHelper class represents a custom tag helper and inherits
from the TagHelper base class, Notice the [HtmlTargetElement] attributed added
to the AutoPostBackTagHelper class. It specifies that the m tag helper will
appear as an attribute named autopostback on the <select> HTML element.
The AutoPostbackTagHelper class contains a boolean property called
autopostback that governs whether the form should be automatically submitted
when the dropdown selection changes.
The Process() method checks the autopostback attribute and accordingly adds a
client side (JavaScript) event handler for the onchange event. What we want to
do in the onchange event handler is to submit the HTML form that houses the
<select> element. To get the reference of the <form> that houses the <select>
element we use this.form property. We then call submit() method to submit it back to the server.
Here is how you can use the AutoPostBack tag helper just created.
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, AutoPostBackDemo
<form asp-controller="Home"
asp-action="ProcessForm" method="post">
<h2>@ViewBag.Country</h2>
<select name="country" autopostback="true">
<option>USA</option>
<option>UK</option>
<option>India</option>
</select>
</form>
The code uses @addTagHelper to add the support for AutoPostBackTagHelper to
the Index view. It then adds a <select> element and sets its autopostback
attribute to true. This way our custom tag helper will be applied to the
<select> element.
When you pick a country from the dropdown list, the form is submitted to the
server and its ProcessForm() action is called.
[HttpPost]
public IActionResult ProcessForm(string country)
{
ViewBag.Country = country;
return View("Index");
}
If you run the application and try selecting different countries you should
see something like this:

That's it for now! Keep coding!!