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
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,
@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,
@using (Html.BeginForm("Search", "Home", FormMethod.Get,
new { target =
"_blank", @class="editForm", data_validatable=true }))
Produces the following HTML
method="get"
target="_blank">
This comment has been removed by a blog administrator.
ReplyDeleteAh so thats how you get around the data- problem. I was using the IDictionary overload to define any attributes that included a data- attribute. I'll have to try it this way.
ReplyDeleteHTML Attributes are property of the elements which may have values and these attribute values are always enclosed in quotes. It’s providing to the browser with some additional information about an elements how the elements should appear or behave. HTML elements can contain one or more attributes, attribute names and attribute values are case-insensitive and separated by an equals (=) sign.
ReplyDelete[HTML Attributes](http://www.willvick.com/HTML/HTMLAttribute.aspx)
[HTML Attributes Examples](http://www.willvick.com/HTML/HTMLExampleAttribute.aspx)
[Youtube - HTML Tutorial - Attributes](http://www.youtube.com/watch?v=ucOXvaCEZgg)