Styling HTML helpers ASP.NET MVC

Dan picture Dan · Sep 3, 2008 · Viewed 54k times · Source

If I have an HTML helper like so:

Name:<br />
<%=Html.TextBox("txtName",20) %><br />

How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?

Answer

Dale Ragan picture Dale Ragan · Sep 3, 2008

You can pass it into the TextBox call as a parameter.

Name:<br/>    
<%= Html.TextBox("txtName", "20", new { @class = "hello" }) %>

This line will create a text box with the value 20 and assign the class attribute with the value hello. I put the @ character in front of the class, because class is a reserved keyword. If you want to add other attributes, just separate the key/value pairs with commas.