Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is what I'm trying with Razor syntax:

<div [email protected]="@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: [email protected].

Razor: enter image description here

Output: enter image description here

Am I out of luck here?

like image 902
QuantumHive Avatar asked Feb 06 '23 16:02

QuantumHive


2 Answers

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 although it functions properly, it can 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 string ToHtmlString()
    {
        return $"{Name}=\"{Value}\"";
    }
}

public class 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>
like image 77
Thorkil Holm-Jacobsen Avatar answered Feb 08 '23 14:02

Thorkil Holm-Jacobsen


Here is a version for ASP.NET Core

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

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

    public void WriteTo(TextWriter writer, HtmlEncoder encoder)
    {
        writer.Write($"{Name}=\"{Value}\"");
    }
}

public static class HtmlHelperExtensions
{
    public static HtmlAttribute Attribute(this IHtmlHelper helper, string name, string value)
    {
        return new HtmlAttribute(name, value);
    }
}
like image 26
Mariusz Jamro Avatar answered Feb 08 '23 14:02

Mariusz Jamro