Let's say I have this code:
<input type="hidden" asp-for="CurrentThread.ThreadId" />
This will generate a hidden input with the name CurrentThread_ThreadId
. However, I would like the name to be "ThreadId"
only. Basically, would like to ignore any parent class and only wanting the name of the last property.
I can easily do:
<input type="hidden" asp-for="CurrentThread.ThreadId" name="ThreadId" />
However, I am losing intellisense.
I was just wondering if there is a something I can do to generate name "ThreadId"
with Intellisense.
Select Tag Helper. This Tag Helpers populate <select> tag of HTML and also associated option elements for the properties of the error. The asp-for attribute of this tag helps is used to mention the model property name of the select element. Similarly, asp-items specify the option element.
The Anchor Tag Helper has introduced many attributes that help us to generate the HTML for Anchor Tag Helper. In this section, we will learn each attribute that can be used with Anchor Tag Helper. It is used to associate the Controller name that is used to generate the URL.
The syntax to register all the tag helpers that are in an assembly is to use asterisk comma (*,) and then the assembly name, Microsoft. AspNet. Mvc. TagHelpers.
You can extend the existing input tag helper to set a custom value for name
attribute.
[HtmlTargetElement("input", TagStructure = TagStructure.WithoutEndTag)]
public class MyTagHelper : Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper
{
[HtmlAttributeName("asp-short-name")]
public bool IsShortName { set; get; }
public MyTagHelper(IHtmlGenerator generator) : base(generator)
{
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (IsShortName)
{
string nameAttrValue = (string)output.Attributes.Single(a => a.Name == "name").Value;
output.Attributes.SetAttribute("name", nameAttrValue.Split('.').Last());
}
base.Process(context, output);
}
}
To register your custom tag helper you need add to _ViewImports.cshtml
:
@addTagHelper *, [AssemblyName]
Then you can use it:
<input type="hidden" asp-for="CurrentThread.ThreadId" asp-short-name="true"/>
Note: As @Stephen Muecke noted the default model binding will not work. You may need to create a custom model binder or use other techniques to retrieve model values from the request
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