Blog

Tagged by 'TextMode'

  • After quite a successful stint in creating some really amazing websites using MVC Razor 5, I had to revert back to working in the world of Web Forms for a new client project. Now I have to deal with .NET web controls, Postbacks and Viewstates.

    When creating a few simple forms consisting of some drop down lists, textboxes and textareas, I noticed wherever I set a "MaxLength" property it would not work. A character limit on my input field would just be ignored in all browsers. I could only replicate this bug when the Max Length property is used alongside the "TextMode" property.

    There were various places where I had the "TextMode" property set to either "Number" or "MultiLine". Soon as this was removed, the value set in "MaxLength" would work.

    How very odd...

    Thankfully, I am not the only person to experience the same issue. Currently, the only way to get around this problem is to add the following JavaScript code (slightly refactored for my own implementation) to check the character length "onKeyDown".

    var ASPNETForm = {
        "CheckTextAreaLength": function(textBox, e, length) {
            var mLen = textBox["MaxLength"];
    
            if (null == mLen)
                mLen = length;
    
            var maxLength = parseInt(mLen);
            if (!ASPNETForm.CheckSpecialKeys(e)) {
                if (textBox.value.length > maxLength - 1) {
                    if (window.event) { //IE
                        e.returnValue = false;
                        return false;
                    }
                    else //Firefox
                        e.preventDefault();
                }
            }
        },
        "CheckSpecialKeys": function(e) {
            if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)
                return false;
            else
                return true;
        }
    }
    

    Add to your ASP.NET TextBox control as so:

    <asp:textbox id="Instructions" MaxLength="50" onkeydown="return ASPNETForm.CheckTextAreaLength(this,event,'50');" runat="server" textmode="MultiLine">
    </asp:textbox>
    

    I am hoping there will be a more elegant solution in ASP.NET 5, or even better, a fix. This problem has been lurking around since 2009!