I need to logout on close page or on close browser ...
as usual ...
but by default ASP Membership wont do it ...
How to make logout when I just leave my site
(FormsAuthentication.SignOut();
HttpContext.Current.Session.Abandon();)
btw got problem on logout button.
here is a code on page render to check if user authorization=true I setup "authorezated panel with logout button"
protected void Page_PreRender()
{
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
Label1.Text = System.Web.HttpContext.Current.User.Identity.Name;
MultiView1.ActiveViewIndex = 0;
}
else
{
MultiView1.ActiveViewIndex = 1;
}
}
but when I click logout
protected void Button2_Click(object sender, System.EventArgs e) //logout
{
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
System.Web.Security.FormsAuthentication.SignOut();
System.Web.HttpContext.Current.Session.Abandon();
MultiView1.ActiveViewIndex = 1;
}
}
Page rendering before logout and I can't see ActiveViewIndex = 1 :(
So I need to click twice on logout button . weird.
There is no request sent to the server when you close a page. There is only a javascript event that fires. So you would have to do a ajax request to do what you need. But I wouldn't depend on that. But if you really need to sign out your user when he closes the page, then that is what you have to do. You can do something like this (if you use jquery):
window.onunload = logOut;
function logOut() {
$.get("[[url to a resource that logs you out]]");
}
About the second problem, I would suggest put the code in your Page_PreRender() in Page_Load() instead.
Related
I’ve made a handy “user control” for login to my website and it is placed in the site master.
The natural procedure is that the user logs in the web site and he should be announced with a welcome message containing its full name. The full-Name naturally should sits in a session variable created when the user logged on.
There is no doubt that we place the desired code in the “page_load” event and expect it to pass user’s full-name to the right circumstances (here its a label named lblFullName) in order to print/show the welcome message when login button clicked, But the full-name doesn’t passed until the user logs in the website again (for the 2nd times).
Why this problem happens?
Its some part of my code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["FullName"]==null)
{
//nothing 2 do.
}
else
{
lblFullName.Text = Session["FullName"].ToString();
}
}
You probably set the Session variable in the user control after the Page_Load event has been processed, so that it will not see the user name until the next postback.
In order to update the Label text as soon as the login is validated, you could:
Define an event in the user control
Register an event handler in the main page
Call the event handler as soon as the user has logged in
In the event handler, update the Label text
You could also eliminate the Session variable by passing the user full name in an EventArgs derived class. If you make the following class accessible in the user control and in the main form:
public class StringEventArgs : EventArgs
{
public string Value { get; set; }
public StringEventArgs(string value)
{
Value = value;
}
}
then you can define this event in the user control:
public event EventHandler<StringEventArgs> UserLoggedIn;
In the function where the login is confirmed, you call the event handlers:
private void UserLoginValidation()
{
// Login validation is done here
bool loginSuccessful = ...
if (loginSuccessful && UserLoggedIn != null)
{
UserLoggedIn(this, new StringEventArgs(fullName));
}
}
In the main page, you register the event handler, which updates the Label:
protected void Page_Load(object sender, EventArgs e)
{
loginUserControl1.UserLoggedIn += loginUserControl1_UserLoggedIn;
...
}
private void loginUserControl1_UserLoggedIn(object sender, StringEventArgs e)
{
lblFullName.Text = e.Value;
}
I'm creating a C# application with a ASP.net frontend, however I'm having a problem at the moment. I want to the user to enter some information, which once submitted, will be displayed within a listbox on the page which works fine. However, once I close the page, stop debugging the program and run it again - the information is still displayed but I want it to start off blank. Here if the ASPX page that I think if causing the issue, it's driving me mad.
public partial class CarBootSaleForm : System.Web.UI.Page, ISaleManagerUI
{
private SaleList saleList;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack && Application["SaleList"] != null)
{
LoadData();
}
else
{
saleList = (SaleList)Application["SaleList"];
}
if (saleList != null)
{
UpdateListbox();
}
}
private void UpdateListbox()
{
lstSales.Items.Clear();
if (saleList != null)
{
for (int i = 0; i < saleList.Count(); i++)
{
lstSales.Items.Add(new ListItem(saleList.getSale(i).ToString()));
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Application.Lock();
Application["SaleList"] = saleList;
Application.UnLock();
Response.Redirect("AddSaleForm.aspx");
}
}
Forget the LoadData() within the page load as it's not actually loading anything at the moment :)
Any help is really appreciated!
The variables stored in Application state are not flushed unless you restart the web server, so you will need to use the iisreset commmand (on command-line) if you are using IIS, or you will need to stop the ASP.NET web server (use the tray icons) after each debugging session.
if it is not postback you can add
Session.Abandon(); in the else block in Page_load.
Kill Session:
How to Kill A Session or Session ID (ASP.NET/C#)
My logout button's code looks like this:
protected void ButtonLogout_Click(object sender, EventArgs e)
{
Session["login"] = null;
}
And my page's onLoad event looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if ((string)Session["login"] != null)
{
ButtonLogout.Visible = true;
// (...)
}
else
{
ButtonLogout.Visible = false;
// (...)
}
}
I'm having problem with this thing working properly. I didn't know what's going on so I've setted up break points in both ButtonClick and PageLoad events. What I found out is that PageLoad event executes first (sic!) and that's why ButtonLogout wasnt hiding after clicking it. I could simply refresh page in ButtonClick event but I'm not sure whether Loading Page twice after 1 button click is OK. Isnt there any other way to solve this?
Thanks.
The issue is that the page life cycle executes in a specific way. In basic terms it goes:
Page_Load
Events fire
Pre_Render
More details can be found - http://msdn.microsoft.com/en-us/library/ms178472.ASPx
If you're setting the visibility of a control you can set this in the Pre_Render page event and at that point the button event will have fired and set what you require.
I recommend you to use asp.net LoginStatus to handle that. And dont forget to clear the session when the user logs out. Checking Using LoginName and LoginStatus Controls will help you.
protected void HeadLoginStatus_LoggingOut(object sender, LoginCancelEventArgs e)
{
Session.Clear();//It clears the session when the user logged out.
Session.Abandon();
FormsAuthentication.SignOut();
}
How can I find out if the user pressed F5 to refresh my page (Something like how SO implemented. If you refresh your page, the question counter is not increased). I have tested many code snippets mentioned in a dozen of tutorials, but none worked correctly.
To be more clear, suppose that i have an empty web form and would like to detect whether the user has pressed F5 in client-side (causing a refresh not submit) or not.
I can use session variables, but if the user navigates to another page of my site, and then comes back , I'd like to consider it as a new visit, not a refresh. so this is not a session-scope variable.
Thanks.
Update: The only workaround I could find was to inherit my pages from a base page, override the load method like below:
public class PageBase : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Session["LastViewedPage"] = Request.RawUrl;
}
}
and in every page if I was interested to know if this is a refresh:
if (this.Session["LastViewedPage"].ToString() == Request.RawUrl)
{
// This is a refresh!
}
I run into this problem and use the following code. It works well for me.
bool isPageRefreshed = false;
protected void Page_Load(object sender, EventArgs args)
{
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
isPageRefreshed = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
}
The only sure solution is to make a redirect to the same page , and here is a similar question: Post-Redirect-Get with ASP.NET
But there are also some other tricks, by adding some ticket on the page and see if this is the same or have change, see the full example and code at:
http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
and one more:
http://dotnetslackers.com/community/blogs/simoneb/archive/2007/01/06/Using-an-HttpModule-to-detect-page-refresh.aspx
I am trying to make an anchor tag cause both client and server validation. I have this code for now:
$(document).ready(function () {
$('div#imgEmailVerifyLoader').hide();
$('a#btn_SubmitContactMessage').click(function ()
{
if (Page_ClientValidate()) // this will trigger all validators on page
{
$('div#imgEmailVerifyLoader').show('slow');
window.Form_OnMasterPage.submit();
return true;
}
else
{
return false;
}
});
});
<a id="btn_SubmitContactMessage" href="Contact.aspx" onclick="Validate();" runat="server">SUBMIT</a>
This performs client validation properly and shows the error message. I have validation controls for each of the textboxes on the page. I also added a server click event handler in code behind for this:
btn_SubmitContactMessage.ServerClick +=new EventHandler(btn_SubmitContactMessage_ServerClick);
}
protected void btn_SubmitContactMessage_ServerClick(object sender, EventArgs e)
{
if (!Page.IsValid)
{
RequiredFieldValidator4.ErrorMessage = "show";
return;
}
}
But when I try to test it by turning off javascript the link(submit) does not postback. Why is that happening?
Now, how do I make sure that validation is being done on the server side to after postback.
I would imagine it's because of the 'onclick=validate()'. Instead of doing that you should register that event inside of '$(document).ready(function ()' like you've got your other JavaScript. That way if JavaScript is not available the form is submitted normally and your server side validation kicks in.