QuantumHive QuantumHive - 22 days ago 6
HTML Question

Define HTML attribute name with razor syntax

With

MVC 5
and
Razor 3
I'm trying to dynamically create an
HTML
Attribute Name with razor syntax, specifically a
data-*
attribute.

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

Example for terminology:



<div data-foo="bar">


Attribute Name:
data-foo


Attribute Value:
bar


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
html
attribute name output is literally:
data-search-@Model.Name
. See:

enter image description here

Am I out of luck here?

Answer

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);
  }
}

Usage:

<div @Html.Attribute("data-search-" + Model.Name, view.Name)></div>