Server Side Yes no confirmation on Page Load in ASP.Net

Last Reply on Dec 15, 2015 09:57 AM By Shashikant

Posted on Dec 14, 2015 02:46 AM

Hi dears;

The article described bellow fine work on Button Click But I want to use On page Load .

http://www.aspsnippets.com/Articles/ASPNet-Server-Side-Yes-No-Confirmation-Box-using-JavaScript.aspx

Posted on Dec 15, 2015 09:57 AM Modified on on Dec 31, 2015 07:40 AM

Hi,

Normally it is not possible, but we can achieve using below code.

As PageLoad is handled at the server, a javascript confirm() is executed on the client after the pageload has been executed.

But you can let the javascript post back to the server again. If you put a hiddenfield control in the page and set its value in your javascript, you can retrieve the value of the field during postback

HTML

<div>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            if (document.getElementById('hfposted').value != '1') {
                if (confirm("Do you want to Acknowledge?")) {
                    document.getElementById('hidField').value = "Yes";
                } else {
                    document.getElementById('hidField').value = "No";
                }
                document.forms[0].submit();
            }
        }); 
    </script>
    <asp:HiddenField ID="hidField" ClientIDMode="Static" runat="server" />
    <asp:HiddenField ID="hfposted" Value="0" runat="server" />
</div>

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        string confirmValue = this.hidField.Value;
        hfposted.Value = "1";
        if (confirmValue == "Yes")
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
        }
        else
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
        }
    }
}

Screenshot