如何在 ASP.NET 应用程序中使用 jQuery 捕获提交事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1230573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:58:03  来源:igfitidea点击:

How to capture submit event using jQuery in an ASP.NET application?

asp.netjquerywebformsform-submit

提问by Herb Caudill

I'm trying to handle the submitevent of a formelement using jQuery.

我正在尝试使用 jQuery处理元素的submit事件form

    $("form").bind("submit", function() {
        alert("You are submitting!");
    });

This never fires when the form submits (as part of a postback, e.g. when I click on a button or linkbutton).

这在表单提交时永远不会触发(作为回发的一部分,例如当我点击一个按钮或链接按钮时)。

Is there a way to make this work? I could attach to events of the individual elements that trigger the submission, but that's less than ideal - there are just too many possibilities (e.g. dropdownlists with autopostback=true, keyboard shortcuts, etc.)

有没有办法使这项工作?我可以附加到触发提交的单个元素的事件,但这不太理想 - 有太多的可能性(例如带有 autopostback=true 的下拉列表、键盘快捷键等)



Update:Here's a minimal test case - this is the entire contents of my aspx page:

更新:这是一个最小的测试用例 - 这是我的 aspx 页面的全部内容:

<%@ page language="vb" autoeventwireup="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:scriptmanager id="ScriptManager" runat="server" enablepartialrendering="true">
                <scripts>
                    <asp:scriptreference path="/Standard/Core/Javascript/Jquery.min.js" />
                </scripts>
            </asp:scriptmanager>
            <p>
                <asp:linkbutton id="TestButton" text="Click me!" runat="server" /></p>
        </div>
    </form>

    <script type="text/javascript">
        $(document).ready(function() {
            alert("Document ready.");
            $("form").submit(function() {
                alert("Submit detected.");
            });
        });
    </script>

</body>
</html>

I get the "Document ready" alert, but not the "Submit detected" when clicking on the linkbutton.

单击链接按钮时,我收到“文档就绪”警报,但没有“检测到提交”。

回答by Herb Caudill

Thanks, @Ken Browning and @russau for pointing me in the direction of hiHymaning __doPostBack. I've seen a couple of different approaches to this:

谢谢,@Ken Browning 和@russau 为我指出劫持 __doPostBack 的方向。我已经看到了几种不同的方法:

  1. Hard-code my own version of __doPostBack, and put it later on the page so that it overwrites the standard one.
  2. Overload Render on the page and inject my own custom code into the existing __doPostBack.
  3. Take advantage of Javascript's functional nature and create a hook for adding functionality to __doPostBack.
  1. 对我自己的 __doPostBack 版本进行硬编码,然后将其放在页面上,以便覆盖标准版本。
  2. 在页面上重载渲染并将我自己的自定义代码注入现有的 __doPostBack。
  3. 利用 Javascript 的功能特性并创建一个钩子来向 __doPostBack 添加功能。

The first two seem undesirable for a couple of reasons (for example, suppose in the future someone else needs to add their own functionality to __doPostBack) so I've gone with #3.

由于几个原因,前两个似乎不受欢迎(例如,假设将来其他人需要将他们自己的功能添加到 __doPostBack),所以我选择了#3。

This addToPostBackfunction is a variation of a common pre-jQuery technique I used to use to add functions to window.onload,and it works well:

这个addToPostBack函数是我用来添加函数的常用 pre-jQuery 技术的变体,window.onload,它运行良好:

addToPostBack = function(func) {
    var old__doPostBack = __doPostBack;
    if (typeof __doPostBack != 'function') {
        __doPostBack = func;
    } else {
        __doPostBack = function(t, a) {
            if (func(t, a)) old__doPostBack(t, a);
        }
    }
};

$(document).ready(function() {
    alert("Document ready.");
    addToPostBack(function(t,a) {
        return confirm("Really?")
    });
});

Edit:Changed addToPostBack so that

编辑:更改 addToPostBack 以便

  1. it can take the same arguments as __doPostBack
  2. the function being added takes place before __doPostBack
  3. the function being added can return false to abort postback
  1. 它可以采用与 __doPostBack 相同的参数
  2. 添加的函数发生在 __doPostBack 之前
  3. 添加的函数可以返回 false 以中止回发

回答by James McCormack

I've had success with a solution with overriding __doPostBack()so as to call an override on form.submit()(i.e. $('form:first').submit(myHandler)), but I think it's over-engineered. As of ASP.NET 2.0, the most simple workaround is to:

我已经通过覆盖解决方案__doPostBack()取得了成功,以便在form.submit()(即$('form:first').submit(myHandler))上调用覆盖,但我认为它是过度设计的。从 ASP.NET 2.0 开始,最简单的解决方法是:

  1. Define a javascript function that you want to run when the form is submitted i.e.

    <script type="text/javascript">
    
    function myhandler()
    {
        alert('you submitted!');
    }
    
    </script>
    
  2. Register your handler function within your codebehind i.e.

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(), 
                                                "myHandlerKey", "myhandler()");
    }
    
  1. 定义一个要在提交表单时运行的 javascript 函数,即

    <script type="text/javascript">
    
    function myhandler()
    {
        alert('you submitted!');
    }
    
    </script>
    
  2. 在您的代码隐藏中注册您的处理程序函数,即

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(), 
                                                "myHandlerKey", "myhandler()");
    }
    

That's all! myhandler()will be called from straightforward button-input submits and automatic __doPostBack()calls alike.

就这样!myhandler()将从简单的按钮输入提交和自动__doPostBack()调用中调用。

回答by Ken Browning

Yeah, this is annoying. I replace __doPostBackwith my own so that I could get submit events to fire.

是的,这很烦人。我__doPostBack用我自己的替换,以便我可以提交事件触发。

Iirc, this is an issue when submitting a form via javascript (which calls to __doPostBackdo) in IE (maybe other browsers too).

Iirc,这是__doPostBack在 IE 中通过 javascript(调用do)提交表单时的问题(也可能是其他浏览器)。

My __doPostBackreplacement calls $(theForm).submit()after replicating the default behavior (stuffing values in hidden inputs)

复制默认行为后我的__doPostBack替换调用$(theForm).submit()(隐藏输入中的填充值)

回答by Powerlord

I don't know how to do it with jQuery, but you could add an OnClientClick property to the ASP.NET control:

我不知道如何使用 jQuery,但您可以向 ASP.NET 控件添加一个 OnClientClick 属性:

<asp:linkbutton id="TestButton" text="Click me!" runat="server" OnClientClick="alert('Submit detected.');" />

回答by fripp13

If you are using .NET Framework 3.5 or up, you can use ScriptManager.RegisterOnSubmitStatement()in your server-side code. The registered script will get called both on normal submit and on DoPostback.

如果您使用 .NET Framework 3.5 或更高版本,则可以在服务器端代码中使用ScriptManager.RegisterOnSubmitStatement()。注册的脚本将在正常提交和 DoPostback 时被调用。

ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "myKey", "SomeClientSideFunction();");

回答by Freeman

This works for capturing the submit:

这适用于捕获提交:

$("form input[type=submit]").live("click", function(ev) {
    ev.preventDefault();
    console.log("Form submittion triggered");
  });

回答by zamoldar

 $(document).ready(function () {

          $(this).live("submit", function () {

                console.log("submitted");
             }
}

回答by Phanindra Kumar

You need to add OnclientClick to linkbutton

您需要将 OnclientClick 添加到链接按钮

OnClientClick="if(!$('#form1').valid()) return false;"

OnClientClick="if(!$('#form1').valid()) 返回 false;"