Sunday, May 4, 2014

Adding custom HtmlAttributes to ASP.NET MVC Razor Views

 

There are a few ways to add custom HtmlAttributes to your ASP.NET MVC Razor Views.  Most often, you will be adding custom HtmlAttributes when you are building out the input fields in your ASP.NET MVC Forms, however, you can add custom HtmlAttributes to any field that you wish.

There are multiple ways to add custom HtmlAttributes to your form elements, however, the only method that actually has Intellisense provided in Visual Studio is the following method:

@Html.CheckBox("terms", new Dictionary<string, object>() {{"id", "terms"}})


In the above example, you declare a Dictionary collection and declare a set of name value pairs by surrounding them in an extra set of curly braces.  Of course, this is a bit of an elongated syntax, therefore, Microsoft also provided a second means of declaring custom HtmlAttributes that is more concise.


Unfortunately, this method, although definitely more concise, does not provide any Intellisense in Visual Studio whatsoever.  In addition, existing Intellisense will often try to mistype the elements in the fields for you, therefore, one should always be careful about what is being typed through this method:



@Html.CheckBox("terms", new {id="terms"})


You may also see variations of the above syntax provided as follows by preceding the attribute with the @ sign



@Html.CheckBox("terms", new {@id="terms"})

Both forms of syntax are valid, however, the preceding syntax without the @ sign can ONLY be used for the id, name and value fields.  All other custom attributes will require the @ sign to work correctly.

No comments:

Post a Comment