QuantumHive QuantumHive - 1 year ago 72
HTML Question

Define HTML attribute name with razor syntax


Razor 3
I'm trying to dynamically create an
Attribute Name with razor syntax, specifically a

So this is about the name of the attribute and NOT the value!!

Example for terminology:

<div data-foo="bar">

Attribute Name:

Attribute Value:

Now that's clear, this is what I'm trying with razor syntax:

<div data-search-@Model.Name="@view.Name">
<div data-search-@(Model.Name)="@view.Name">

Neither examples are recognized by Razor and are rendered as is. So the
attribute name output is literally:
. See:

enter image description here

Am I out of luck here?

Answer Source

I think that the reason it doesn't work is, that @ is actually a valid character for an attribute in HTML5, and therefore Razor will not activate "code-mode" in this exact scenario. You could achieve what you are trying to do by building the attribute name completely in Razor code as follows:

<div @("data-search-" + Model.Name)="@view.Name">

However, this is not particularly pretty and can also cause Visual Studio and ReSharper to complain about a missing attribute name. Instead I would probably make a helper function:

public class HtmlAttribute : IHtmlString
    public string Name { get; }
    public string Value { get; }

    public HtmlAttribute(string name, string value)
        Name = name;
        Value = value;

    public override string ToHtmlString()
        return $"{Name}=\"{Value}\"";

public static HtmlHelperExtensions
  public static HtmlAttribute Attribute(this HtmlHelper helper, string name, string value)
      return new HtmlAttribute(name, value);


<div @Html.Attribute("data-search-" + Model.Name, view.Name)></div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download