How to specify data attributes in razor, e.g., data-externalid=23151 on @this.Html.CheckBoxFor(...)
@Html.CheckBoxFor(
m => m.MyModel.MyBoolProperty,
new {
@class = "myCheckBox",
data_externalid = "23521"
}
)
The _
will automatically be converted to -
in the resulting markup:
<input type="checkbox" name="MyModel.MyBoolProperty" data-externalid="23521" class="myCheckBox" />
And that's true for all Html helpers taking a htmlAttributes
anonymous object as argument, not only the CheckBoxFor
helper.
Unable to apply attributes to a checkBoxFor
I changed the html attribute data-partId
to data_partId
. You can refer the link. And also modified the dynamic id part.
@Html.CheckBoxFor(x => x.Parts[i].MoveAll, new { @id = "all" + "@part.ID", @class = "part-class", data_partId = "@part.ID" })
What is the HTML attributes parameter?
HTML elements can have attributes. For example:
<div class="some-css-class" data-foo="bar" />
Here the div
's attributes are class
and data-foo
.
Razor's various HTML helper functions that accept an htmlAttributes
argument translate the provided object to attributes.
You can utilize this using an anonymous type where its properties are translated to attributes names, and their values to the respective attribute's value.
For example:
new
{
@class = "some-css-class",
data_foo = "bar"
}
This will translate to the attributes shown above.
Underscores in property names get translated to dashes (How to specify data attributes in razor, e.g., data-externalid="23151" on @this.Html.CheckBoxFor(...)), and the @
before @class
is required because class
is a reserved keyword that can't be used without escaping it with an @
(How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?).
There's also an overload accepting IDictionary<string, object> htmlAttributes
, so you could instead pass a dictionary as well:
new Dictionary<string, object>
{
{ "class", "some-css-class" },
{ "data-foo", "bar" }
}
Adding AutoComplete attribute to textbox in Razor
I don't think there is a standard way to manipulate html attributes from ViewModel attributes with the EditorFor
extension method.
However, you can create a custom html helper method if you want to keep it DRY.
Btw I don't think that it would be a great idea to encapsulate these kind of informations (html attributes) inside a ViewModel class.
Related Topics
How to Set Attributes Values Using Reflection
If My Interface Must Return Task How to Have a No-Operation Implementation
How to Check If a Property Exists on a Dynamic Anonymous Type in C#
Find Methods That Have Custom Attribute Using Reflection
Why Does Computing Factorial of Relatively Small Numbers (34+) Return 0
How to Get Xml Node from Xdocument
How to Return 401 Instead of 302 in ASP.NET Core
Show Controls Added Programmatically in Winforms App in Design View
What Is the Best Battleship Ai
Memorycache Does Not Obey Memory Limits in Configuration
Converting String to Float in C#