So this article is about the HTML helpers and the HTML they generate and how much control you have, now we all know how to write attributes on a HTML tag, but with HTML helpers how can we do it ??
1) Most Html helpers take HtmlAttributes object as a parameter, which is nothing but we pass in an anonymous object into the parameter and then the helper uses the "Property Name and Value" from the object as the attribute name and value on the html tag.
ex:
@using (Html.BeginForm("Search", "Home", FormMethod.Get,
new { target = "_blank" }))
{
<** input type="text" name="q" />
<** input type="submit" value="Search" />
}
would generate
Similarly, the second method is the overload in the Html helpers which takes an IDictionary
which is also the same and use the dictionary keys as the attribute names and the object as the value.
new Dictionary<string, object>(){
{ "key", "value" },
{ "key1", someObj },
{ "blah", 1 }
} )
Both these approaches have some tricky bits, that is what I am writing this post for
For example, setting the class attribute of an element requires you to have a property named class on the anonymously typed object, or as a key in the dictionary
of values. Having a key value of “class” in the dictionary is not a problem, but it is problematic for
an object, because class is a reserved keyword in C# and is not available to use as a property name
or identifier, so you must prefix the word with an @ sign:
Ex:
@using
(Html.BeginForm("Search", "Home", FormMethod.Get,
new { target =
"_blank", @class="editForm" }))
Another problem is setting attributes with a dash in the name (like data-val). Dashes are not
valid in C# property names, but all HTML helpers convert an underscore in a property name to a
dash when rendering the HTML.
Ex:
@using
(Html.BeginForm("Search", "Home", FormMethod.Get,
new { target =
"_blank", @class="editForm", data_validatable=true }))
Produces the following HTML
method="get"
target="_blank">