How do I create a TagHelper whose value is a Property Model (without using @Model)?

Tag Helper is one of the nice features of Asp.Net Core. I have created several tag helpers and they can be very helpful.

Now I would like to try something more advanced. Attributes of tag attributes can be created so that the attribute value is a property of the model.

And an example of this:

 //model
 public class MyModel{
      public int MyField {get;set;} = 10;
 }



  //in the view
  @model MyModel
   ...
  <input asp-for="MyField" />

      

In the above example, the tag asp-for

for the tag input

refers to a property from the model. The documentation says that

The asp-for attribute value is the model expression and the right side of the lambda expression. Hence, asp-for = "Property1" becomes m => m.Property1 in the generated code, so you don't need to prefix with Model.

So this is pretty cool and this same documentation seems to be called "Expression Name".

How do I create such a property in my own tag helper?

+3


source to share


1 answer


Just declare the parameter in your TagHelper by type ModelExpression

and then use it to create content.

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 like this:



@model TestModel

<foo for="Id"></foo>
<foo for="Val"></foo>

      

And pass the model of the type new TestModel { Id = "123", Val = "some value" }

, then you will get the following result 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>

      

+3


source







All Articles