Is there any appropriate method to clear a server side session on client side. I use java script to clear a session, but when ever a page is redirected then server side session
You Can Use Page Methods in javascript
PageMethods.EndSession();
[WebMethod()]
public static void EndSession()
{
HttpContext.Current.Session.Abandon();
}
Dont Forget to set EnablePageMethods
to true
of Script Manager.
What you can do is "Invoke a Server side page from javascript and Clear the session there".
If you are using jQuery, It is simple as this
<a href="somepage.aspx" id="logout">Logout</a>
<script type="text/javascript" >
$(function(){
$("#logout").click(function(e){
e.preventDefault();
$.post("logout.aspx",function(data){
//now do something in client side. May be show a message to user
alert("Succesfully logged out");
});
});
});
</script>
Assumung inside the logout.aspx page load event, you are clearing the Session. You may need to update some part of your UI( Logged in user name, some liknks etc..) once the user is logged out.
The reason why this happens is while page is being parsed, it always looks for the server side tags and execute it first. Its same as parsing server side control. So even if you have written the code, to fire on click event of any button, the code would execute every time its loaded. Even if you try to comment the code in server tag, the code would be executed.
function Clear_() {
// '<%=Session["UID"]=""%>';// still this line executes alert('ok'); } </script>
The answer to your problem is NO. The sessions are stored as server side, then how could you clear it clide side. You have to make AJAX request to server and clear the session on server
UPDATE 2
Its same as the aspx page is parsed for server control. These server tags need to be processed while the request is at server and then evaluated the value. For example, if you want some value in javascript to be populated from some session value on the server.
//in javascript
var myValue = <%= Session["SomeVal"] %>
So when the page is parsed, the value inside server tags are evaluated and replaced with their actual value(For control, its replaced with html). So in the final output, that is sent to client, the following markup would be sent
//in javascript
var myValue = 50;
You could verify by looking in the "View Source" from the browser.
I think it is not possible to delete session from client side bcz Session is server side. One thing may be possible if we clear all the cookies from the client browser then may be session also deleted bcz when we create a session asp.net genrates a session id which is stored in the client browser if we succeed in deleting asp.net session cookie then may be session is also deleted.
Hello you can try with this code
function Clear()
{
location.href="logout.aspx";
}
In code behind file logout.aspx.cs
Session.Clear();