Tag Helper's are one of the sweet features of Asp.Net Core. I have created several tag helpers and they can be super helpful.
Now I would like to try something a bit more advanced. Tag helper attributes have the ability to be created in such as way that the attribute value is a model property.
And example of this is the following:
//model
public class MyModel{
public int MyField {get;set;} = 10;
}
//in the view
@model MyModel
...
<input asp-for="MyField" />
In the above example the asp-for
tag helper for the input
tag directed references a property from the model. The documentation says that
The asp-for attribute value is a ModelExpression and the right hand side of a lambda expression. Therefore, asp-for="Property1" becomes m => m.Property1 in the generated code which is why you don't need to prefix with Model.
So this is pretty cool, and that same documentation appears to call this an "Expression name".
How do I create such a property in my own custom tag helper?
To create custom tag helper, the first step is to create a class that inherits from "TagHelper" class. This class has a virtual method to generate HTML tags. It contains both synchronous (Process) and asynchronous (ProcessAsync) implementation of the virtual method.
Unlike HtmlHelpers, a tag helper is a class that attaches itself to an HTML-compliant element in a View or Razor Page. The tag helper can, through its properties, add additional attributes to the element that a developer can use to customize the tag's behavior.
The Input Tag Helper binds an HTML <input> element to a model expression in your razor view.
@addTagHelper makes Tag Helpers available The code above uses the wildcard syntax ("*") to specify that all Tag Helpers in the specified assembly (Microsoft. AspNetCore. Mvc. TagHelpers) will be available to every view file in the Views directory or subdirectory.
Just declare the parameter in your TagHelper as of type ModelExpression
and then use it to generate the contents.
For example:
public class FooTagHelper : TagHelper
{
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div";
output.Content.SetHtmlContent(
$@"You want the value of property <strong>{For.Name}</strong>
which is <strong>{For.Model}</strong>");
}
}
If you use it in a view like this:
@model TestModel
<foo for="Id"></foo>
<foo for="Val"></foo>
And pass a model like new TestModel { Id = "123", Val = "some value" }
then you will get the following output in your view (formatted for clarity):
<div>
You want the value of property <strong>Id</strong>
which is <strong>123</strong>
</div>
<div>
You want the value of property <strong>Val</strong>
which is <strong>some value</strong>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With