Powered by Blogger.

Thursday, February 27, 2014

Show confirmation dialogbox using JavaScript in Asp.Net



In this post we will discuss how we can show confirmation message on button click using JavaScript in Asp.Net.

Also you can check out my previous posts on:

- Query to get records between two dates in sql server 2008

- Properties in C#.Net

- Get user control value in aspx page in asp.net

We can show confirmation message on button click by using JavaScript.

First we will write the JavaScript function like below inside the </head> tag and then we will put the button inside the form tag. So our code will be like below:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function deleteConfirmation() {
            if (confirm("Are you sure you want to delete this record?") == true)
                return true;
            else
                return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click"/>
        </div>
    </form>
</body>
</html>

Then we can register the JavaScript to the button in the Page_Load like below:

btnDelete.Attributes.Add("onclick", "return deleteConfirmation();");

So the full code will be like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default10 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnDelete.Attributes.Add("onclick", "return deleteConfirmation();");
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {

    }
}

When user clicks on the button the confirmation message will come like below:

When user click on OK then the server side OnClick (btnDelete_Click) will excute. If user click on Cancel, then the server side OnClick will not execute.





0 comments

Post a Comment