简体   繁体   中英

Asp linkbutton always triggering OnClick event

I have an asp link button:

<asp:LinkButton ID="lnkEdit" runat="server" onclick="Edit_Click" ClientIDMode="Static" OnClientClick="confirm()">Edit</asp:LinkButton>

var modalWin = new ModalPopupWindow();
function confirm() {
    var text = document.getElementById('lnkEdit').innerText;
    if (text == "Undo Changes") {
        modalWin.ShowConfirmationMessage("Any unsaved work will be discarded. Do you want to continue?", 200, 200, "Confirmation", "", "Ok", btn1ClickHandler, "Cancel", btn2ClickHandler);
    }
    else {
        return true;
    }
};

If I click the linkbutton, it will show me the modal.ShowConfirmationMessage . When I click the Ok on the modal , that's the time it should consider the OnClick event.

The problem here is it is firing both OnClientClick and OnClick . It will show the modal pop then the page posts back even if i didn't click any button yet.

The handlers:

function btn1ClickHandler() {
    // Ok button
        return true;
    }
function btn2ClickHandler() {
        // Cancel button
    }

You need your Javascript code to return false in the OnClientClick event if the modal was Cancel/No. That will prevent the page posting back for the server OnClick event.

Or simply:

OnClientClick="return confirm()"

you can use if to check whether OK button is clicked or not like this

if(modalWin.ShowConfirmationMessage("Any unsaved work will be discarded. Do you want to continue?", 200, 200, "Confirmation", "", "Ok", btn1ClickHandler, "Cancel", btn2ClickHandler))
{
  //Your code for Post_back as Ok button is clicked

}
else
{
  //Do Nothing as cancelled button is clicked.
   return false;
}

I solved it by adding return false on the if statement and also by using return confirm()"

function confirm() {
        var text = document.getElementById('lnkEdit').innerText;
        if (text == "Undo Changes") {
            modalWin.ShowConfirmationMessage("Any unsaved work will be discarded. Do you want to continue?", 200, 200, "Confirmation", "", "Ok", "btn1ClickHandler();", "Cancel", "btn2ClickHandler();");
            return false;
        }
        else {
            return true;
        }
    };

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