Refer the below code only works with chrome and ie.
SQL
CREATE TABLE [dbo].[UserSessionEndTime](
[UserId] [int] NOT NULL,
[TimeOutTime] [datetime] NULL
)
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function doUnload() {
$.ajax({
type: "POST",
url: "WebForm1.aspx/InsertLogOutTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
}
</script>
</head>
<body onunload="doUnload()">
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Code
[WebMethod]
public static void InsertLogOutTime()
{
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO UserSessionEndTime VALUES(@UserId,@TimeOutTime)", con))
{
con.Open();
cmd.Parameters.AddWithValue("@UserId", 1);
cmd.Parameters.AddWithValue("@TimeOutTime", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Screenshot