class and data-* Attributes in MVC

The htmlAttributes parameter is used a lot in HtmlHelper functions in your MVC views. These are great… however, what about when you want to set the class attribute or create a custom data-* attribute?

In C#, class is a reserved word and hyphens (-) are forbidden in variable names – so how can we define them in a dynamic object?

Fortunately, there are work-arounds. (phew!)

  • Reserved words can be prefixed with an apetail (@ – ‘apetail’ is my new favourite word for the ‘at sign’)
  • Hyphens (-) in data attributes can be replaced with underscores (_). These are swapped out for hyphens when compiled as HTML.

Example

@Html.DropDownList("ddlName", list, new { @class = "myDropDown", data_val= true, data_val_required = "Please select a value."})

becomes

      ...

Can’t find the MSDN documentation for this. If anyone does, please post a comment!

Advertisements
Posted in MVC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s