Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify custom name for asp-for (Need only the child property)

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.

like image 634
JohnC1 Avatar asked Feb 19 '18 09:02

JohnC1


People also ask

What is ASP for tag?

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.

Which of these helpers is used to specify name of controller form will redirect to?

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.

Which is the correct syntax of tag helper in form tag?

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.


1 Answers

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

like image 126
AlbertK Avatar answered Oct 03 '22 06:10

AlbertK