65.9K
CodeProject 正在变化。 阅读更多。
Home

扩展 ASP.NET 多行文本框控件以限制输入的字符数

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.74/5 (42投票s)

2007年8月31日

CPOL

2分钟阅读

viewsIcon

195494

downloadIcon

926

开发者几乎在所有 Web 项目中使用多行文本框控件。由于当 TextMode 属性设置为 Multiline 时,TextBox 控件的 MaxLength 属性不起作用,我们通常使用验证器控件来验证长度。

引言

开发者几乎在所有 Web 项目中使用多行 TextBox 控件。由于当 TextMode 属性设置为 Multiline 时,TextBox 控件的 MaxLength 属性不起作用,我们通常使用验证器控件来验证长度。 在这篇实践文章中,我们将使用 JavaScript 扩展 TextBox 控件,以限制用户输入的字符数到指定的长度。

使用代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Globalization;
using System.Threading;

namespace CustomServerControls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:TextArea runat="server"></{0}:TextArea>")]
    public class TextArea : TextBox
    {
        public override TextBoxMode TextMode
        {
            get
            {
                return TextBoxMode.MultiLine;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (MaxLength > 0)
            {
                if (!Page.ClientScript.IsClientScriptIncludeRegistered("TextArea"))
                {
                    Page.ClientScript.RegisterClientScriptInclude("TextArea", 
                                      ResolveUrl("~/textarea.js"));
                }
                this.Attributes.Add("onkeyup", "LimitInput(this)");
                this.Attributes.Add("onbeforepaste", "doBeforePaste(this)");
                this.Attributes.Add("onpaste", "doPaste(this)");
                this.Attributes.Add("onmousemove", "LimitInput(this)");
                this.Attributes.Add("maxLength", this.MaxLength.ToString());
            }
                base.OnPreRender(e);
        }
    }
}

上面的代码通过扩展 ASP.NET 的 TextBox 控件创建了一个新的 TextArea 自定义服务器控件。 通过重写 OnPreRender 函数,我们将属性包含到控件的 HTML 中。 我们添加了自定义 JavaScript 和一个属性,以在客户端传递 MaxLength

为了展示工作的 TextArea 控件,我准备了以下 HTML

<%@ Page Language="C#" AutoEventWireup="true" 
         CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="csc" Namespace="CustomServerControls" %> 

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>TextArea Custom Server Control with MaxLength property</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <csc:TextArea id="TextArea" runat="server" 
            MaxLength="105" Rows="10" 
            Width="300px"></csc:TextArea>
    </div>
    </form>
</body>
</html>

在上面的 HTML 中,我通过使用以下行注册了自定义控件到网页

<%@ Register TagPrefix="csc" Namespace="CustomServerControls" %>

如果您不想在每个使用 TextArea 控件的页面上添加上面的注册行,您可以在 web.config 文件的 system.web 节中添加以下语句

<pages>
   <controls>
    <add tagPrefix="csc" namespace="CustomServerControls"></add>
   </controls>
</pages>  

我将控件添加在页面上,如下所示

<csc:TextArea id="TextArea" runat="server" MaxLength="105" Rows="10" Width="300px">
</csc:TextArea>

让我们比较一下多行文本框控件和我们的文本区域控件的渲染输出

标准多行 ASP.NET TextBox 的渲染输出是

<textarea name="TextArea" id="TextArea" rows="10" cols="20" style="width:300px;" ></textarea>

我们的 TextArea 自定义服务器控件的渲染输出是

<textarea name="TextArea" rows="10" cols="20" id="TextArea"
  onkeypress="LimitInput(this)" onbeforepaste="doBeforePaste(this)"
  onpaste="doPaste(this)" onmousemove="LimitInput(this)" maxLength="105"
  style="width:300px;"></textarea>

JavaScript 事件处理程序 doBeforePastedoPaste 仅在 Internet Explorer 中实现。 这些事件处理程序用于检查使用鼠标在 Internet Explorer 中粘贴的字符长度。 遗憾的是,doBeforePastedoPaste 事件处理程序未在其他浏览器中定义,我们无法在 IE 以外的浏览器中捕获鼠标粘贴。 因此,我添加了一个 onmousemove 事件处理程序,以检查使用鼠标移动后用鼠标粘贴的字符长度。 onkeypress 事件处理程序处理标准字符输入。

function doBeforePaste(control)
{
   maxLength = control.attributes["maxLength"].value;
   if(maxLength)
   {
       event.returnValue = false;
   }
}
function doPaste(control)
{
   maxLength = control.attributes["maxLength"].value;
   value = control.value;
   if(maxLength){
        event.returnValue = false;
        maxLength = parseInt(maxLength);
        var o = control.document.selection.createRange();
        var iInsertLength = maxLength - value.length + o.text.length;
        var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
        o.text = sData;
    }
}
function LimitInput(control)
{
    if(control.value.length >

更新

© . All rights reserved.