Search code examples
cssasp.net-mvchtml-helper

Styling HTML helpers ASP.NET MVC


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?


Solution

  • 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.