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.
<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:
Output:
Am I out of luck here?
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>
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With