grokky
grokky

Reputation: 9285

How can I use tag helpers to get a model property's name on an arbitrary element?

ASP.NET Core.

 <label asp-for="FooModelProperty">...</label>

This generates a form control with the appropriate property name. Same for select, input, etc.

But I need that name on some random element, e.g. a div, so I can use it in JavaScript. And the problem is asp-for tag helper doesn't work on an arbitrary element.

So how do I do something like this:

<div asp-for="FooModelProperty">...</div>

Upvotes: 3

Views: 1798

Answers (1)

Will Ray
Will Ray

Reputation: 10889

The ModelExpression class was created to help with cases like these. You can add it as a property to your TagHelper and access the property name from there.

Here's an example:

[HtmlTargetElement("*", Attributes = forName)]
public class NameAppenderTagHelper : TagHelper
{
    private const string forName = "na-for";

    [HtmlAttributeName(forName)]
    public ModelExpression PropertyName { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        // add the property name as an attribute to the element
        output.Attributes.Add("data-property-name", PropertyName.Name);

        // if you'd like the [Display] name value, you can use this:
        // output.Attributes.Add("data-property-name", PropertyName.Metadata.DisplayName);
        base.Process(context, output);
    }
}

When used in Razor like this:

<div na-for="MyProperty"></div>

It will output:

<div data-property-name="MyProperty"></div>

Upvotes: 6

Related Questions