Search code examples
asp.net-core-tag-helpers

How to supply tag helper attribute from model value


I have a tag helper that includes an attribute whose value is an enumeration:

public class MyElementTagHelper : TagHelper
{
    public MyAttribute MyAttribute { get; set; }
}

public attribute MyAttribute { apple, banana, cherry }

This allows me to create an HTML <my-element> tag that takes a my-attribute attribute, like this:

<my-element my-attribute="apple">

My question is: Suppose my view model looks like this:

public class MyViewModel
{
    public MyAttribute MyAttribute { get; set; }
}

Is there any way to use the MyAttribute value from the view model as the value to the HTML attribute, kind of like this:

<my-element my-attribute="Model.MyAttribute">

More generally, is there a way to reference a variable as the attribute value?


Solution

  • [Answering my own question]

    Simply introduce the C# variable with an "@" inside of the quote marks, like this:

    <my-element my-attribute="@Model.MyAttribute">
    

    (I posted the question because I was certain that this wouldn't work. I'm pretty sure I had tried this a few months ago and it didn't work. Either I'm loosing my mind - a distinct possibility - or this is new stuff added in the last several months.)