Styling HTML helpers ASP.NET MVC

57,330

Solution 1

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.

Solution 2

This is how to add a class and a style on the same element...

"x" being the model passed to the view with a property of TextBoxID

@Html.TextBoxFor(x => x.TextBoxID, new { @class = "SearchBarSelect", style = "width: 20px; background-color: green;" })

Solution 3

I did some research and came across this article that seems to have a solution to your question.

Ajax Control Toolkit with ASP.NET MVC#

source: jimzimmerman

ARTICLE LINK

http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=330

QUOTE

So basically if you put the class name TextboxWatermark on any textbox input with the title you like to show as the watermark like this:

<input type="text" class"TextboxWatermark" name="username" id="username" title="Must be at least 6 chars" />

or

<%= Html.TextBox("username", new { @class = "TextboxWatermark", @title = "Must be at least 6 chars" }) %>

What is nice about the second option is that you get the added benefit of getting the View Engine to fill out the value of the textbox if there is an item in ViewData of the ViewData.Model that has a var named 'username'.

Solution 4

Use the htmlAttributes parameter with an anonymous type, like tihs:

<%=Html.TextBox("txtName","20", new { @class = "test"}) %>
Share:
57,330
Dan
Author by

Dan

Updated on August 03, 2022

Comments

  • Dan
    Dan almost 2 years

    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?