ASP.NET Core MVC : using custom tag helpers

292 Views Asked by At

I have a custom tag helper defined like so:

public class TextQuestionTagHelper : TagHelper
{
    private readonly HtmlHelper _htmlHelper;

    [HtmlAttributeName("asp-for")]
    public ModelExpression For { get; set; }

    public string Question { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }

    public TextQuestionTagHelper(IHtmlHelper htmlHelper)
    {
        _htmlHelper = htmlHelper as HtmlHelper;
    }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        var partial = await _htmlHelper.PartialAsync(
            "Tags/TextQuestion",
            new TextQuestionViewModel
            {
                Question = Question,
                Description = Description
            });
    }
}

In the template Tags/TextQuestion I have:

@model TextQuestionViewModel

<p>@Model.Question</p>
<p>@Model.Description</p>
@Html.TextBoxFor(m => m)

Notice how I have a property For I'm wondering how to do I map this to the TextBoxFor inside my custom template and then render that view for the tag helper? I can't find any examples online

1

There are 1 best solutions below

2
Fengzhi Zhou On

First define your taghelper

//add a maxlength validation for example
[HtmlTargetElement("input", Attributes = "asp-for")]
public class TextQuestionTagHelper : TagHelper
{
    public override int Order { get; } = int.MaxValue;

    [HtmlAttributeName("asp-for")]
    public ModelExpression For { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);

        ...
    }

    private static int GetMaxLength(IReadOnlyList<object> validatorMetadata)
    {
        ...
    }
}

Then in the model

public class TextQuestionViewModel
{
    [Display(Name = "Question")]
    [Required]
    [MaxLength(5, ErrorMessage = "Foo cannot be longer than 5 characters.")]
    public string Question { get; set; }
    [Display(Name = "Question")]
    [Required]
    [MaxLength(10, ErrorMessage = "Foo cannot be longer than 10 characters.")]
    public string Description { get; set; }
    public string Image { get; set; }
}

In the view

<input asp-for="Question" data-val="true" />

Remember to add the taghelper in _ViewImports

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@addTagHelper *, yourProject

The input limit is set

enter image description here

And the page

enter image description here