检测被失败的客户端验证阻止的AJAX回发 [英] Detect AJAX Postback Blocked By Failed Client-Side Validation

查看:87
本文介绍了检测被失败的客户端验证阻止的AJAX回发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery水印插件(watermark-1.2.jquery.min.js)使文本框具有水印文本(例如,文本框将显示为"First Name",但是当用户单击文本框).除了一个小问题,它在大多数情况下都可以正常工作.

我在将EnableClientScript设置为true的文本框中有一些验证器(例如RequiredFieldValidator).这意味着当文本框不包含有效数据时,不会发生AJAX回发(例如,当我单击同一验证组中的按钮时).对我来说幸运的是,水印插件在回发之前清除了水印.但是,当验证失败并阻止了回发时,这是一个问题,因为即使没有发生回发,该插件也会清除水印.

我希望ASP.NET提供一个JavaScript事件,以便我可以截获失败的客户端验证并重新启用水印.

请注意,我目前正在使用 add_pageLoaded 来检测AJAX回发后的页面加载,工作正常.我只需要弄清楚当单击a按钮但回发中止时如何调用一些代码.

在最坏的情况下,我只能禁用客户端验证,但我宁愿不这样做.

这是一些示例代码来演示该问题(您可以忽略JavaScript的巨大代码块,因为我刚刚嵌入该代码块,因此您可以在没有外部依赖项的情况下运行它):

I''m using a jQuery watermark plugin (watermark-1.2.jquery.min.js) to make textboxes have watermark text (e.g., the textbox will read as "First Name", but gets cleared when the user clicks the textbox). It''s working fine for the most part, except for one niggling issue.

I have a few validators (e.g., RequiredFieldValidator) on the textboxes with EnableClientScript set to true. This means that when the textboxes don''t contain valid data, an AJAX postback does not occur (say, when I click a button in the same validation group). Lucky for me, the watermark plugin clears the watermark before postback. However, that is a problem when validation fails and the postback is prevented, as the plugin clears the watermark even though a postback didn''t occur.

I am hoping there is a JavaScript event ASP.NET provides so I can intercept a failed client-side validation and re-enable the watermark.

Note that I''m currently using add_pageLoaded to detect a page load after an AJAX postback and that is working fine. I just need to figure out how to call some code when the a button is clicked but the postback is aborted.

In the worst case, I can just disable client-side validation, but I''d rather not do that.

Here is some sample code to demonstrate the issue (you can ignore the giant block of JavaScript, as I just embedded that so you can run this without external dependencies):

<%@ Page Language="vb" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
  <title>Sample of Blocked Ajax Postback Issue</title>
</head>
<body>
  <form runat="server">
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
    <!-- Contents of watermark-1.2.jquery.min.js -->
    <script type="text/javascript">
      (function (a) {
        var b = { init: function (c) {
          var d = this; return this.each(function (f) {
            var e = { watermarkText: "Enter Text", watermarkCss: "watermarkCss", disableAutocomplete: false };
            f === 0 && a(document.forms).bind("submit.watermark", d, b.formSubmit);
            c && a.extend(e, c); if (a(this).val().length === 0) e.isWatermarked = true;
            if (e["disableAutocomplete"] === true) a(this).attr("autocomplete", "off");
            else a(this).removeAttr("autocomplete");
            a(this).data("settings", e).bind("keypress.watermark", b.keypressProcessing).bind("focus.watermark",
            b.focusProcessing).bind("blur.watermark", b.blurProcessing).blur()
          })
        }, keypressProcessing: function () {
          var b = a(this).data("settings"); b.isWatermarked = false
        }, focusProcessing: function () {
          var b = a(this).data("settings");
          (a(this).val().length == 0 || a(this).val() == b.watermarkText && b.isWatermarked) &&
          a(this).val("").removeClass(b.watermarkCss)
        },
        blurProcessing: function () {
          var b = a(this).data("settings"); if (a(this).val().length == 0) {
            a(this).val(b.watermarkText).addClass(b.watermarkCss); b.isWatermarked = true
          }
        }, formSubmit: function (b) {
          a.each(b.data, function () {
            var b = a(this).data("settings"); a(this).val() == b.watermarkText && b.isWatermarked &&
            a(this).val("")
          })
        }
      }; a.fn.watermark = function (c) {
        if (b[c]) return b[c].apply(this, Array.prototype.slice.call(arguments, 1));
        else if (typeof c === "object" || !c) return b.init.apply(this, arguments);
            else a.error("Method " + c + " does not exist on watermark.") } })(jQuery)
    </script>
    <asp:ScriptManager runat="server" ID="mainManager" EnablePartialRendering="true" />
    <asp:UpdatePanel runat="server" UpdateMode="Conditional">
      <ContentTemplate>
        <p>
          <asp:TextBox ID="txtEmail" runat="server" />
          <asp:RequiredFieldValidator runat="server" ControlToValidate="txtEmail" Display="Dynamic"

            EnableClientScript="true" Text="*" ValidationGroup="Group1" />
          <asp:RegularExpressionValidator runat="server" ControlToValidate="txtEmail" Display="Dynamic"

            EnableClientScript="true" Text="*" ValidationGroup="Group1" ValidationExpression=".+@.+\..+" />
        </p>
        <p>
          <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Group1" />
        </p>
      </ContentTemplate>
    </asp:UpdatePanel>
    <script type="text/javascript">
      Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function () {
        $("#" + "<%= txtEmail.ClientID %>").watermark({
          watermarkText: "Email",
          watermarkCss: "active_watermark"
        });
      });
    </script>
  </form>
</body>
</html>

推荐答案

(" + " ).watermark({ watermarkText:" , watermarkCss:" }); }); < / 脚本 > < /form > < /body > < /html >
("#" + "<%= txtEmail.ClientID %>").watermark({ watermarkText: "Email", watermarkCss: "active_watermark" }); }); </script> </form> </body> </html>


有点疯狂,我强烈不建议您将其作为最终解决方案,但可能会给您一些想法:

覆盖javascript WebForm_DoPostBackWithOptions函数.

Kind of crazy, and I highly don''t recommend this as a final solution, but might give you some ideas:

override the javascript WebForm_DoPostBackWithOptions function.

<script type="text/javascript">
    //<![CDATA[
    var oldDoPostBack = WebForm_DoPostBackWithOptions;
    WebForm_DoPostBackWithOptions = function(options) {
        if (Page_ClientValidate(options.validationGroup))
        {
            options.validation = false;     // Don''t validate twice
            oldDoPostBack(options);         // Call original post back function
        }
        else
        {
            alert("Validation Failed");
        }
    };
    //]]>
</script>



也许将其与您的add_pageLoaded代码放在同一脚本块中.



Maybe put this in the same script block as your add_pageLoaded code.


这篇关于检测被失败的客户端验证阻止的AJAX回发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆