MichaelWare.Net

A Blog on Software and Technology

NAVIGATION - SEARCH

Custom Attributes When Using Html.TextBoxFor

I finnally got a few minutes to work on the new asp.net mvc 2 this weekend.  I was working through the example on Model Validation Scott Guthrie did on Jan 15th and found my self wanting to resize the text boxes on my input form.  In his example he is using Html.TextBoxFor and calling into his model object for the attributes of the input tag.  This seemed really nice and I worked with it.  Since I wanted to resize the input boxes I started trying to put a class into the parameters of TextBoxFor since it has two overloads with htmlAttributes.  After some fiddling I decided to google, this turned up some questionable advice such as "Don't be afraid of using raw HTML" which sounds a bit like hard coding it just because you don't know how.  My search continued.  I decide I would take a look futher down the comments of ScottGu's post and found the answer there (mostly).  He said about half way down you should use the following syntax:

This seemed to work but I was trying to add a class attribute so I could affect the text boxes.  I tried the following. 

This will not compile.  After a looking at this for a minute its clear that class is a keyword.  Simple work around below.

This got me right where I wanted to be.  I had a class attribute on my input boxes that I could reference in my css.  This would be the end of a happy story if after applying my css it had updated the look of my text boxes.  After a quick look in fire bug I found my page css was being overridden by a site level setting. 

Since this was a change I would not mind having site wide I thought about chaning it there or adding a input[type="text"] to my pages css.  The only draw back to this is IE6 does not support this style of input selector.  I decided to go with the class element since it works in all the browsers I have to support (IE6 is still 20% of the traffic on our sites).

 

Comments (5) -

Thanks a lot. Works perfectly.

Very nice!
About drove me bananas until I found your post.
Thanks, Michael.

The following code work for me. You may try this as well.

<%= Html.TextBoxFor(model => model.Title, new { @class="width250" })%>

Worked as expected, Helped me a lot. Keep up the good work.

Thanks
Jayawant

You Rock.  thanks.

Comments are closed