简体   繁体   中英

ASP.NET PostBack after AJAX response

I'm working with a legacy web application - there's a form with some text inputs and some file inputs, and the form is saved on a PostBack..

HTML:

<input id="txt1" name="txt1" type="text" />
<input id="hfd1" name="hfd1" type="hidden" value="-1" />
<input id="file1" name="file1" runat="server" type="file" />
<asp:Button ID="btnSave" runat="server" OnClientClick="return PrepareSave()" OnClick="btnSave_Click" Text="Save" />

JS:

function PrepareSave() {
    $('#hfd1').val($('#txt1').val());
    return true;
}

I need to send an AJAX request inside PrepareSave() to validate a field on the server, and depending on the response, carry on with the PostBack or don't. I've tried this:

function PrepareSave() {
    Project1.Web.Services.AJAXService1.CheckSomething(someString, function (result) {
        if (result == true) {
            // continue PostBack
            $('#hfd1').val($('#txt1').val());
            return true;
        }
        else {
            // abort PostBack
            alert('invalid');
            return false;
        }
    });
}

But it's failing - it doesn't post back regardless of the AJAX response. I've tried implementing the accepted answer here but it's having the same problems. What can I do to make it work?

I've tried simplifying that accepted answer above, to test it:

<asp:Button ID="btnSave" runat="server" ClientIDMode="Static" OnClientClick="PrepareSave(); return false;" Text="Save" />
<asp:Button ID="btnSaveHidden" runat="server" ClientIDMode="Static" OnClick="btnSave_Click" Visible="False" />

function PrepareSave() {
    $('#btnSaveHidden').click(); // does nothing. also tried .trigger('click')
}

In code behind you can do:

ClientScript.RegisterStartupScript(GetType(), "ReloadParent", "window.parent.location.href = window.parent.location.href;", true);

or in js, use the script part by itself:

window.parent.location.href = window.parent.location.href;

hth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM