Why The MaxLength Property Isn't Working For Your ASP.NET TextBox

So, you've written a web page in ASP.NET, placed an asp:TextBox control on the page, and set it's MaxLength property -- but when you run the site and go to that page, you find that you can type in as much text as you want. What's going on here?

The answer: you set the TextMode property to "MultiLine".

Here's what's happening: when ASP.NET renders a page to the browser, it converts server-side controls to their HTML equivalents. In the case of an asp:TextBox control with the TextMode property set to "MultiLine", the control is rendered not as an <input> control, but rather a <textarea> control. And the HTML specification for the <ltextarea> control does not include a maxlength property.

So it all makes sense, though it would be nice if the compiler would catch this and generate an error -- otherwise, this could sneak by unnoticed and cause problems with your site later.


Popular Posts

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

A Red Herring When Using Moq to Mock Methods With Optional Parameters

Unit Testing with a Mock Entity Framework DbContext and Fake DbSets