views:

170

answers:

4

I would like to limit a textbox to 10 characters in MVC.

<label ID="lbl2" runat="server" Width="20px"></label>
<%=Html.TextBox("polNum") %>    
<label ID="lbl1" runat="server" Width="10px"></label>

I know you can set the Max Length property in .net. How do I do that in MVC with a textbox generated this way?

A: 

You need to set some html properties... something like:

<%=Html.TextBox("polNum",null, new {maxlength=10}) %>

good luck

Paul
Actually, you don't need this overload. You can skip the null and go with the two-argument version.
Will
A: 

Use the overload of the TextBox method which is getting Html attributes :

Html.TextBox( "polNum", "value", new { maxlength="10" } );
Canavar
A: 

Do it in plain HTML:

<%= Html.TextBox("polNum", null, new { @maxlength = "25" }) %>

(The null parameter is because you don't want a default value...)

Tomas Lycken
A: 
<%=Html.TextBox("polNum", new { maxlength = 10 }) %>

http://msdn.microsoft.com/en-us/library/dd492984.aspx

HtmlHelper uses reflection to examine the anonymous type. It converts the fields of the type into attributes on the, in this case, TextBox control. The resulting HTML looks like

<Textbox id="polNum" maxlength =10 />

You can use the anonymous type to add other relevant attributes, such as

new { @class = "MyCssClass", type = "password", value="HurrDurr", 
      textmode="multiline" }
Will
In XHTML all attributes should be lower cased, so maxlength instead of MaxLength
Jan Jongboom
OH DEAR lemme fix that sorry I caused your webpage to blowed up.
Will