How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Some examples I found that apparently worked with older versions of mvc suggest that there was a length parameter of sorts:

<%=Html.TextBox("test", 50)%>

But that may have been mistakenly setting the value.

How do this work in the current release? Passing in the style doesn't appear to have any effect.


Solution 1:

The original answer is no longer working as written:

<%=Html.TextBox("test", new { style="width:50px" })%> 

will get you a text box with "{ style="width:50px" }" as its text content.

To adjust this for the current release of MVC 1.0, use the following script (note the addition of the second parameter - I have mine starting as blank, adjust accordingly based on your needs):

<%=Html.TextBox("test", "", new { style="width:50px" })%> 

Solution 2:

For this you have to use HtmlAttributes, but there is a catch: HtmlAttributes and css class .

you can define it like this:

new { Attrubute="Value", AttributeTwo = IntegerValue, @class="className" };

and here is a more realistic example:

new { style="width:50px" };
new { style="width:50px", maxsize = 50 };
new {size=30, @class="required"}

and finally in:

MVC 1

<%= Html.TextBox("test", new { style="width:50px" }) %> 

MVC 2

<%= Html.TextBox("test", null, new { style="width:50px" }) %> 

MVC 3

@Html.TextBox("test", null, new { style="width:50px" })

Solution 3:

Something like this should work:

<%=Html.TextBox("test", new { style="width:50px" })%>

Or better:

<%=Html.TextBox("test")%>

<style type="text/css">
    input[type="text"] { width:50px; }     
</style>

Solution 4:

I -strongly- recommend build your HtmlHelpers. I think that apsx code will be more readable, reliable and durable.

Follow the link; http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.aspx

Solution 5:

Don't use the length parameter as it will not work with all browsers. The best way is to set a style on the input tag.

<input style="width:100px" />