ASP.NET confirm before executing codebehind

2019-01-19 11:30发布

I have a form where a user can delete a record, and I want a pop up message where the user has to click okay to confirm the delete.

Delete button:

<asp:Button ID="btnDelete" runat="server" Text="Delete" UseSubmitBehavior="false" OnClick="btnDelete_Click" OnClientClick="confirmation();" />

Confirmation function:

function confirmation() {
        var answer = confirm("Are you sure you want to delete? This action cannot be undone.")
    }

So right now, clicking the delete button executes the btnDelete_Click Sub in the code behind regardless of whether you click okay or cancel in the pop up box. I know I can add if (answer) { -- some code here -- } in my javascript function, but is it possible to use javascript to execute code from the codebehind? Or is there another way to do this?

11条回答
虎瘦雄心在
2楼-- · 2019-01-19 12:02

We can easily do this by using ConfirmButtonExtender,

<ajaxToolkit:ConfirmButtonExtender ID="cbeDelete" TargetControlID="btnDelete" ConfirmText="Are you sure you want to delete? This action cannot be undone." runat="server">

Its very simple...

查看更多
唯我独甜
3楼-- · 2019-01-19 12:04

Put this in your aspx code:

OnClientClick="return confirm('Are you sure you want to delete this project?');" 
查看更多
我只想做你的唯一
4楼-- · 2019-01-19 12:13

I know this is old post, but you can put the above answers into one line like this. And you don't even need to write the function.

 <asp:Button runat="server" ID="btnDelete" Text="Delete" OnClick="btnDelete_Click" OnClientClick="if ( !confirm('Are you sure you want to delete ? ')) return false;"  />
查看更多
干净又极端
5楼-- · 2019-01-19 12:16

Yet another way to achieve this would be using the AJAX Toolkit ConfirmButton Extender, as shown here:

http://www.ezineasp.net/Samples/ASP-Net-AJAX-cs/Control-Toolkit/AJAX-ConfirmButton-Control/Default.aspx

查看更多
戒情不戒烟
6楼-- · 2019-01-19 12:20

please use this sample:

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return ConfirmOnDelete();"/>

<script type="text/javascript">    
   function ConfirmOnDelete() {
    if (confirm("Do you really want to delete?") == true)
        return true;
    else
        return false;
   }
</script>
查看更多
太酷不给撩
7楼-- · 2019-01-19 12:20

I think above should work if you are not able to use it with Button, Try the <asp:link button>. Mine works just fine.

ASPX page:-

<asp:LinkButton  ID="takeActionBtn" CausesValidation="false" runat="server" 
        onclientclick="return confirm('Do you really want to perform Action ?');"> Take Action </asp:LinkButton>

VB server codebehind:-

Protected Sub takeActionBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles takeActionBtn.Click

End Sub

One thing I noted is that if you are using control (ascx) within a page you may need to to off/on at page or control level AutoEventWireup="false" <%@ control in <%@ page

Good Luck !!

查看更多
登录 后发表回答