jQuery: form.submit(fn) does not work with Asp.net

2019-02-24 15:22发布

I am trying to attach an event handler to form.submit on asp.net rendered pages with no success. I want to intercept every postback, and doc. says that I should be able. Am I doing something wrong?

$(document).ready(function() {
    $("form").submit(function() {
            alert('Form submit');
            debugger;
    });
});

3条回答
爷的心禁止访问
2楼-- · 2019-02-24 16:07

This is something I did on a legacy WebForm application:

//trigger jquery form submit event handlers on __doPostBack
$(function() {
    var oldPostBack = __doPostBack;
    __doPostBack = function() {
        $("form").triggerHandler("submit");
        oldPostBack.apply(this, arguments);
    };
});

This allows you to wire "submit" events using jQuery the way you normally would:

$("#myForm").submit(function() { alert("submitted!"); });

Typical doPostBack hijacking, but only once. It triggers "submit" handlers on any form elements before doing the old postback. This is necessary because, while asp.net does call the onsubmit function attached to the form dom object, it doesn't look like jquery's events work that way.

查看更多
放荡不羁爱自由
3楼-- · 2019-02-24 16:14

Don't know if you are still looking for it, but here is the solution I have. I don't think it works with event canceling if using, say, stopPropagation() but it will let you run some script before submitting the form.

<script type="text/javascript">
    $(function () {
        var oldSubmit = __doPostBack;
        var newSubmit = function (eventTarget, eventArgument) {
            alert('custom submit function');
            return oldSubmit(eventTarget, eventArgument);
        };
        __doPostBack = newSubmit;
    });
</script>
查看更多
Explosion°爆炸
4楼-- · 2019-02-24 16:26

asp.net webforms are generally enveloped in only one big form (hence the term web forms).

if I'm not mistaken, all links and submit buttons call __doPostBack manually, so it bypasses the calling form submit and delegates that responsibility to the __doPostBack function.

you would probably need to overwrite this function.

<script type="text/javascript"> 
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
    theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script> 

though I'm trying to understand your "debugger;" line in your function. perhaps it should be this?

$(document).ready(function() {
    $("form").submit(function() {
            alert('Form submit');
    });
}); 
查看更多
登录 后发表回答