Delete data from database on Browser (Tab) Close using JavaScript and C# in ASP.Net

Last Reply 10 months ago By dharmendr

Posted 10 months ago

On closing browser tag delete particular data from sql database

Please any solution



Posted 10 months ago

Hi aspsun11,

To delete particular data on browser close follow the below steps.

1. After successfull Login set Session variable to identify the user. In the example i have used IsValidLogin and UserId.

2. Then create a JavaScript function to make AjaxCall to a page for delete the record on browser close.

3. Then call the JavaScript function and pass the required parameter.

Check this example. Now please take its reference and correct your code.


function AjaxCall(userId) {
    var webUrl = 'Delete_Record.aspx?UserID=' + userId;
    var xmlHttpObject = null;
    try {
        // Firefox, Opera 8.0+, Safari...
        xmlHttpObject = new XMLHttpRequest();
    catch (ex) {
        // Internet Explorer...
        try {
            xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
        catch (ex) {
            xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
    if (xmlHttpObject == null) {
        window.alert('AJAX is not available in this browser');
    }"GET", webUrl, false);


<asp:Button Text="Login" runat="server" OnClick="Validate" />


protected void Validate(object sender, EventArgs e)
    // If Valid Login.
    if (1 == 1)
        Session["IsValidLogin"] = true;
        Session["UserId"] = "12345";


<html xmlns="">
<head runat="server">
    <script src="BrowserCloseCall.js" type="text/javascript"></script>
    <script type="text/javascript">
        window.onunload = function () {
            AjaxCall('<%= Session["UserID"] %>');
    <form id="form1" runat="server">


using System.Configuration;
using System.Data;
using System.Data.SqlClient;


private void Page_Load(object sender, System.EventArgs e)
    // If user logged in.
    if ((bool)Session["IsValidLogin"])
        // If UserId is exists.
        if (!string.IsNullOrEmpty(Request.QueryString["UserID"]))
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
                using (SqlCommand cmd = new SqlCommand("DELETE FROM Table WHERE UId = @UserId"))
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@UserId", Request.QueryString["UserID"]);
                    cmd.Connection = con;

After login IsValidLogin and UserId is set and redirect to Default page.

When user close browser AjaxCall is executed inside window.onunload function and Session["UserID"] is passed and Delete_Record page called and record deleted from table.