Skip to content Skip to sidebar Skip to footer

Conditional Confirm Prompt In Asp.net Code Behind

I have looked around for a way of implementing this. Here is a pseudocode representation of what I have: bool hasData = ItemHasData(itemid); Confirm = 'false'; // hidden variable

Solution 1:

One method I end up using in some situations is to have a Panel that displays the Confirm / Cancel buttons. This avoids the need to handle JavaScript events and uses ASP.NET entirely.

<asp:Panel ID="pDeleteConfirm" runat="server"
    CssClass="AlertDialog"
    Visible="False">
    <p>Do you wish to delete the selected record?<br />
    <asp:Button ID="btDeleteYes" runat="server" OnClick="btDelete_Click" Text="Delete" />
    <asp:Button ID="btDeleteNo" runat="server" OnClick="btDelete_Click" Text="Cancel" />
    </p>
</asp:Panel>

<asp:GridView ID="gvData" runat="server"
    AutoGenerateColumns="False" 
    CssClass="GridView"
    DataKeyNames="ID"
    DataSourceID="sqlData"
    EmptyDataText="There is no data entered in the system."
    OnRowDeleting="gvData_RowDeleting">
    ......
</asp:GridView>

I use the OnRowDeleting event to show the Panel

protected void gvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    // Show confirmation dialog
    pDeleteConfirm.Visible = true;

    // Select the row to delete
    gvData.SelectedIndex = e.RowIndex;

    // Cancel the delete so the user can use the confirm box
    e.Cancel = true;
}

Handle the button Click events

protected void btDelete_Click(object sender, EventArgs e)
{
    Button bt = (Button)sender;
    switch (bt.ID)
    {
        case "btDeleteYes": // they confirmed a delete
            sqlData.Delete();
            break;

        case "btDeleteNo": // they clicked cancel
            // Do nothing
            break;

        default:
            throw new Exception("Unknow button click in btDelete_Click");
    }
    // clear selection and hide the confirm box
    gvData.SelectedIndex = -1;
    pDeleteConfirm.Visible = false;
}

This isn't JavaScript but you can add in some UpdatePanels to do AJAX work on it.

Just one method to do it through ASP.NET rather than JavaScript handling.


Solution 2:

The job of your code-behind is to render HTML out to the browser. It does this, and then the socket is closed and your server side code is no longer executing.

You'll have to implement this logic using a Javascript function on the client side.

Are you attempting to warn the user if there's data loaded before they take a certain action? Or perhaps before they try to leave the page? You'll have to popup the alert using script when that action happens on the page.


Post a Comment for "Conditional Confirm Prompt In Asp.net Code Behind"