I have a custom tag helper and I want to use the asp-for attribute in it, but it renders something else:
public class FormerTagHelper : TagHelper
{
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div";
output.Content.AppendHtml($@"<input class=""form-control"" asp-for=""{For}""> </input>");
}
}
<former asp-for="Name"></former>
It renders following in the HTML:
<div>
<input class="form-control" asp-for="Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression">
</div>
Edit: My goal is to achieve this cshtml with the custom tag
<form method="post">
<div class="mt-2">
<label class="form-label">Name</label>
<input class="form-control" asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span> <br />
</div>
</form>
<div class="mt-3">
<button type="submit" class="btn-primary">Send</button>
</div>
Which renders following HTML in the browser:
Your provided code worked right out of the box but looking at these questions I might wonder if it can be simplier:
Adding default tag ('asp-for') in custom tag helper
Resolve asp-for in custom tag helper
ASP.NET Core creating custom input tag helper
ASP.NET Core MVC : using custom tag helpers
Edit2 My goal is to achieve this cshtml with the custom tag
<form method="post">
<div class="mt-2">
<label class="form-label">Name</label>
<input class="form-control" asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span> <br />
</div>
</form>
<div class="mt-3">
<button type="submit" class="btn-primary">Send</button>
</div>
Which renders following HTML in the browser:
<div class="mt-3"
<label class="form-label" for="Name">Name</label>
<input class="form-control" type="text" data-val="true" data-val-length="The field Name must be a string with a maximum length of 255." data-val-length-max="255" data-val-required="The Name field is required." id="Name" name="Name" value="">
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true">
</span>
</div>

To dynamically generate the
<input>element withasp-forattribute you need theInputTagHelper.IHtmlGeneratorservice into the DI container by adding to Startup.cs or Program.cs.To generate the
<input>element, you needInputTagHelper.Render
inputTagHelperOutputin<div>.