How to write a custom ASP.NET 5 host tag that contains other tags

I looked at examples on taghelpers in google, but could not find any example that I am looking for.

I have the following code:

<div class="form-group"> <label asp-for="PersonName" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="PersonName" class="form-control" /> <span asp-validation-for="PersonName" class="text-danger"></span> </div> </div> 

What I would like to do is replace it with something like

 <bootstraprow asp-for="PersonName"></bootstraprow> 

However, I'm not sure I wrote a taghelper containing other taghelpers

  • Is it possible?
  • If possible, provide an example code above.

Edit: this is not the same as storing variables in custom taghelpers, but I want to call other custom taghelpers or existing taghelpers.

+5
source share
1 answer

If we check what you have, the only property is PersonName. As for the markup itself, everything else is good old HTML.

Therefore, you do not need to replace anything. You need to have a constructor that is dependent on IHtmlGenerator . This will be automatically entered and you can create different tags based on your model.

Relevant IHtmlGenerator Signature:

 public interface IHtmlGenerator { ... TagBuilder GenerateValidationMessage( ViewContext viewContext, string expression, string message, string tag, object htmlAttributes); TagBuilder GenerateLabel( ViewContext viewContext, ModelExplorer modelExplorer, string expression, string labelText, object htmlAttributes); TagBuilder GenerateTextBox( ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, string format, object htmlAttributes); ... } 

What is it!

Here is some code that would capture the main tag:

 [HtmlTargetElement("bootstraprow")] public BootstrapRowTagHelper: TagHelper { protected IHtmlGenerator Generator { get; set; } public InputTagHelper(IHtmlGenerator generator) { Generator = generator; } [HtmlAttributeName("asp-for")] public ModelExpression For { get; set; } [HtmlAttributeNotBound] [ViewContext] public ViewContext ViewContext { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { //todo: write your html generating code here. } } 

Here's a repo with sample code that generates Bootstrap HTML from TagHelpers:

https://github.com/dpaquette/TagHelperSamples/blob/master/TagHelperSamples/src/TagHelperSamples.Bootstrap/

+1
source

Source: https://habr.com/ru/post/1235685/


All Articles