Posted by: Cirilo Meggiolaro | 05/2/2009

Tip of the day #200 – ASP.NET MVC – Defining html attributes for Html Helpers

Define an html attribute for controls created via html helpers is pretty straightforward. The ASP.NET MVC Html helpers have overloads that help you out to define properties such as control style, css class, enable / disable state and so on.

How to…

The basic way to do that is to pass either an IDictionary<string, object> to a HtmlHelper that will bind the properties with the values defined on the dictionary. Another way is to use the object initializer syntax to define the properties you want to check.

Let’s assume we want to define the style of a TextBox by setting its width and height, a tooltip text and an input max length:

<%= Html.TextBox(“FullName”, “”, new { title = “Enter your full name”, maxlength = 200, style = “width: 250px;” }) %>

If you want to define a css class you may use the class keyword. There is one problem though: the class keyword is reserved to be used by the .NET framework. One workaround is to add a @ symbol before the keyword. Your control will be similar to the following:

<%= Html.TextBox(“FullName”, “”, new { title = “Enter your full name”, maxlength = 200, @class = “StyleClassName” }) %>

Advertisements

Responses

  1. Thanks this was simple and helpful.

  2. Thanks a lot. It proved very useful information to me.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: