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

删除回忆录丶 提交于 2019-12-01 18:57:39

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>

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.

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');
    });
}); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!