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

ASP.NET 自定义验证摘要

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.38/5 (17投票s)

2004年10月23日

5分钟阅读

viewsIcon

287183

downloadIcon

2222

用您自己可自定义的弹出摘要窗口替换丑陋的 ValidationSummary 控件文本。

引言

验证是 ASP.NET 中一项极其有用的功能。Microsoft 提供的强大验证控件允许开发人员用最少的代码轻松地验证表单数据。更具体地说,ValidationSummary 控件提供了一种简单的方法来显示页面上所有验证错误的摘要列表。然而,此控件通常以与页面其余部分在美学上不兼容的方式呈现错误。能够将所有验证错误弹出一个可自定义以匹配您网站主题的窗口将非常有用。通过 JavaScript 和对您的 <asp:ValidationSummary> 标记的一些修改,这当然是可能的。本文将向您展示如何制作一个可自定义的弹出验证摘要窗口,例如以下窗口

Sample screenshot

“丑陋”的 ValidationSummary 控件

因此,您想在 ASP.NET 页面上使用验证。您创建表单,添加一些 TextBox、一些 RequiredFieldValidator 和一个 ValidationSummary 来完善您的用户界面并为用户提供相对友好的消息。

然而,令您沮丧的是,您发现 ValidationSummary 是您页面上的一个丑陋的污点。另一方面,也许您对控件的外观还满意,但只是没有多余的屏幕空间来容纳 ValidationSummary 控件。

The ugly ValidationSummary control

如果有一种方法可以将所有验证控件的消息提取出来,然后弹出一个您自己的自定义错误窗口怎么办?事实证明,有几种方法可以做到这一点。当然,您可以设置 ValidationSummary 控件的 ShowMessageBox 属性,但这仍然相当丑陋,而且肯定不可自定义

Sample screenshot

我们不会重写 ValidationSummary 服务器控件,而是利用现有控件和一些简单的 JavaScript,来生成我们自己的自定义错误消息,以通知最终用户他们需要对其表单进行的更改。

修改 WebUIValidation.js

首先,您需要找到 WebUIValidation.js 文件。在 ASP.NET 1.1 中,它应位于 X:\Inetpub\wwwroot\aspnet_client\system_web\1_1_4322 目录中。如果您运行的是其他版本的 ASP.NET,则可能需要搜索该文件。找到后,用您喜欢的编辑器打开该文件。

在我们开始之前,我们需要在文件中添加一个函数来 URL 编码文本字符串。这将确保在通过查询字符串传递消息时不会出现问题。此函数是从此处借用的。

/* URL encodes a string, making it suitable to pass in a query string.
Borrowed from http://www.rgagnon.com/jsdetails/js-0096.html. */
function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, 
           '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27');
}

我们将只关注 ValidationSummaryOnSubmit() 函数。此函数负责迭代您放置在 ASP.NET 表单上的各种验证控件,并打印这些控件的错误消息。在该函数中,您会看到以下条件语句

if (summary.showmessagebox == "True") {

在紧邻该行之前是插入代码的好地方。

// If a custom popup is desired, and a URL was specified ... 
if ((summary.showcustompopup == "True") &&
    (typeof(summary.customurl) == "string"))
{
    var width;
    var height;

    // Width, height are passed in the customwidth and customheight properties.
    width = (typeof(summary.customwidth == "int") ? summary.customwidth : "200");
    height = (typeof(summary.customheight == "int") ? summary.customheight : "200");

    // The query string that will be passed to the custom URL.
    s = "";

    // Iterate through each error, adding them to s, and separating by a '|'.
        for (i=0; i<Page_Validators.length; i++) 
            if (!Page_Validators[i].isvalid && 
                 typeof(Page_Validators[i].errormessage) == "string") 
            s += (Page_Validators[i].errormessage) + 
                 ((i == (Page_Validators.length - 1)) ? "" : "|");

        // Build the query string.
    s = summary.customurl + "?err=" + URLencode(s);

    // If an icon was specified, add it to the query string.
    if (typeof(summary.icon) == "string")
        s += "&icon=" + URLencode(summary.icon);

    // If a header was specified, add it to the query string.
    if (typeof(summary.customheader) == "string")
        s += "&header=" + URLencode(summary.customheader);

    // If a page title was specified, add it to the query string
    if (typeof(summary.customtitle) == "string")
        s += "&title=" + URLencode(summary.customtitle);

    /* Check if the caller requested a modal dialog,
     * and use the appropriate method to open the window.  Note that 
     * modal dialogs currently only work in Internet Explorer 5.0+ */
    if (summary.modal == "True")
        window.showModalDialog(s,"","dialogWidth:" + width + 
               "px;dialogHeight:" + height + "px;status:no;");
    else
        window.open(s, null, "height=" + height + ",width=" + 
               width + ",status=no,toolbar=no,menubar=no,location=no");
}

创建已验证表单

保存 WebUIValidation.js 并打开 Visual Studio .NET。创建一个新的 ASP.NET Web 应用程序,并在表单上添加一些 TextBox 控件和一个 Button 控件。确保将 ButtonCausesValidation="True" 属性设置为“True”。接下来,为每个 TextBox 添加一个 RequiredFieldValidator 控件。将其 ErrorMessage 属性设置为描述性消息(例如,“名字不能为空。”),并将其 Text 属性设置为简单的星号('*')。另外,请务必将每个验证器的 ControlToValidate 属性设置为其各自的控件。

最后,添加一个 ValidationSummary 控件。将 ShowMessageBoxShowSummary 都设置为 False。现在,切换到 HTML 模式并找到 ValidationSummary 标记。我们编写的 ValidationSummaryOnSubmit() 可以接受并传递给弹出页面的属性有很多

属性 描述
showcustompopup 指示显示自定义弹出窗口。
customurl 自定义弹出页面的 URL。
customwidth 弹出窗口的宽度。
customheight 弹出窗口的高度。
customheader 弹出窗口顶部的标题文本。
customtitle 弹出窗口标题栏中的文本。
模态 是否将弹出窗口显示为模态表单。仅在 IE 5.0+ 中有效。
icon 要在弹出窗口中显示的图标。

下面显示了一个自定义 ValidationSummary 标记的示例

<asp:ValidationSummary class=code id=vsmSummary ForeColor="DarkRed" 
 runat="server" showcustompopup="True" customurl="Msgbox.aspx" 
 customwidth="225" customheight="250" customheader="Attention!" 
 customtitle="Error on Form" modal="True" icon="warning" ShowSummary="False"/>

您需要做的最后一件事是创建弹出页面——即弹出并向用户显示错误消息的页面。这仅仅是读取 Request.QueryString 值和格式化文本的问题。您可以在本文随附的代码中查看此页面。

上面的 ValidationSummary 标记将产生类似以下内容的内容

Custom Validation Summary

最终产品 - 优缺点

因此,现在我们有了一个可自定义的错误消息,它不会像 ValidationSummary 控件那样改变或占用我们表单上的屏幕空间。但是,此技术存在缺点。显然,如果最终用户没有启用 JavaScript,他们将不会收到弹出窗口。然而,在这个时代,这已不再是一个日益严重的问题,即使没有弹出窗口,每个表单字段旁边显示的星号仍然会提醒用户他们的错误。

另一个可能更常见的问题是弹出窗口阻止程序。如果用户启用了此类功能,他们可能看不到您的弹出窗口。但是,同样,显示的星号将有助于缓解此问题。最后,如果您尝试显示模态弹出窗口,只有 Internet Explorer 5.0 或更高版本的用户才能收到它。

因此,这种方法既有优点也有缺点。虽然它可能不是确保跨浏览器兼容性的最佳选择,但它可以成为专业网站的一个不错的补充,让您可以自定义错误消息以匹配您网站的主题,或者也许根据用户错误输入的表单字段显示自定义帮助。

查看实时演示.

© . All rights reserved.