asp.net cookie not saved - c#

Can you please tell me what am I doing wrong here.
Why the Cookie data is not stored when I reload the page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// it is always null !!!!
if (Response.Cookies["user_id"].Value != null)
{
//code never gets here
}
}
}
and this is the code for storing the cookie (after clicking a checkbox):
protected void CheckBoxRememberMe_Click(object sender, EventArgs e)
{
Response.Cookies["user_id"].Value = tbUserID.Text;
Response.Cookies["user_id"].Expires = DateTime.Now.AddDays(15);
}
So: I click on the checkbox, the value of tbUserID textbox is stored in the HttpCookie, then I reload the page (refresh) and the value is null.
Any idea ?

When checking for the cookie you want to be making a request rather than adding the cookie to the response.
if (Request.Cookies["user_id"].Value != null)
{
//code should get here
}

Related

asp.net Load Child page only from parent page

I have two pages MainPage.aspx and ChildPage.aspx. From main page when i click a button i redirect to ChildPage.
If i give the address of ChildPage directly on browser, i do not want to load it directly instead i want to redirect to MainPage.
the ChildPage must be loaded only if it is loaded from the MainPage.
How do I find from where the ChildPage.aspx is loaded. how to find the parent page of it or from where it is loaded.
can we try something in the below code
if (!IsPostBack)
{
if (finding_source)
{
Response.Redirect("MainPage.aspx");
}
}
You can use Request.UrlReferrer.AbsolutePath to see the previous page.
if (!IsPostBack)
{
if (Request.UrlReferrer != null && Request.UrlReferrer.AbsolutePath == "/MainPage")
{
//do what you want
}else{
Response.Redirect("~/MainPage.aspx");
}
}
TIP But be careful with using it with postbacks since it will change the value of Request.UrlReferrer to the current page during a postback.
Even though your question is not clear , here i am trying to give my solution.
MAINPAGE.ASPX BUtton Click
protected void lnkRegister_Click(object sender, EventArgs e)
{
Session["MainPage"] = "true";//Encrypt it if u wish
Response.Redirect("childpage.aspx");
}
CHILDPAGE.ASPX PAGE LOAD
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Session["MainPage"] as string) && Session["MainPage"].Tostring()=="true")
{
//proceed
}
else
{
Response.Redirect("mainpage.aspx");
}
}
GLOBAL.ASAX
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
Session.RemoveAll();
Session.Clear();
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
it is little difficult to control browser shutdown or close...but you can workaround global asax file when your application shutsdown.

Redirect to page on button click

Hi I am trying to redirect to the previous page on button click but things are not going so well here is my code:
private string previousPage = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
protected void BackButton_Click( object sender , EventArgs e )
{
Response.Redirect(previousPage);
}
When I first get directed to this page the previousPage variable stores the correct URL but after I click on the button for some reason previousPage value is change to the curent page url and i get sent back to the curent page.
What am I doing wrong here and how can I corect it?
EDIT
I wrapped the code like this:
if(!IsPostBack)
{
if( Request.UrlReferrer != null ) {
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
And I get redirected to a page that I did not create and has a link.On the page is written:
Object moved to here.
"here" is a link and when I cliked it I get sent back to the page I pressed the button
When you have a postback, the referrer is the page itself, so this is expected behaviour :-)
One solution would be to have something like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) Session["prev"] = Request.UrlReferrer.ToString();
if(Session["prev"] == null) {some code that disables the back button goes here!}
}
protected void BackButton_Click( object sender , EventArgs e )
{
Response.Redirect(Session["prev"] as string);
}
The reason why this answer works and the others posted so far do not, is that I am using Session["prev"] to remember the most recent valid referrer. So the trick is to 1) realise that when you have a postback the referer is url of the page itself (which the OP did) and 2) remember the last non-post referrer URL so that you can use it when the Back button is pressed.
You need to test for a postback. When you click the button the page is posted back to the server and the referrer becomes the page you are on and the value you want is overwritten.
private string previousPage = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
}
protected void BackButton_Click( object sender , EventArgs e )
{
Response.Redirect(previousPage);
}
you forgot put it in IsPostBack that y its working like this
if(!IsPostBack)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
code like this to work with it...
When you click on your button, the page load is executed before the click event, so it is resetting the value of your previousPage variable. You need to wrap it in a check to make sure it's not been posted back, like so:
if (!IsPostBack) {
previousPage = Request.UrlReferrer.ToString();
}
I am the last to answer but was first to comment
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
}

Getting Session Value in Master Page - PageLoad

I have a master page on which I have a dropdown of Language. I save dropdown's selected value in session. and want to check on page load that what's the value in session. But it gives exception because on page load, there is nothing in session.
Can anyone tell me what method should I call before page load in which I can set session to a default value?
Thanks in advance.
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Language"] = ddlLanguage.SelectedValue;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlLanguage.SelectedValue = Session["Language"].ToString();
}
You could initialize your session variable to a default value inside the Page_Init event. So by the time the Page_Load event is fired, at least you would have a value to check against.
Alternatively, you could just check the Session variable for a null value in the Page_Load event & not try and use its value if indeed it is null.
For this second option, change your code to be something like:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlLanguage.SelectedValue = Session["Language"] == null ? "0" : Session["Language"].ToString();
}
Replace the zero in the true condition of the ternary operator with whatever default value you have in your dropdown list.
You have to check it before using it because when you are trying to get the value from the session it is null and not assigned any value yet.
if (Session["Language"] != null)
{
ddlLanguage.SelectedValue = Session["Language"].ToString();
}
No need to set default option in page init event, you can set language dropdown in page load event also like this ways :
Master page Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["culture"] != null)
ddlLanguage.SelectedValue = Session["culture"].ToString();
else
{
ddlLanguage.SelectedValue = "en-US";
Session["culture"] = "en-US";
}
}
}
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Session["culture"] = ddlLanguage.SelectedValue;
}
=================
By this way I can preserve selected language in session and can use in whole application.
You could use Page_PreLoad event to set your session variable's value...

What is the best way to distinguish beteen "Refresh Post" or a "Real Post Back"

What is the best way to distinguish beteen "Refresh Post" or a "Real Post Back".
This is what I need to attain
protected void Button1_Click(object sender, EventArgs e)
{
if(PostBack && !Refresh)
{
//Do Something
}
}
I usually do a Response.Redirect to the same page in the postback event.
That way all my Page.IsPostBack are real Postbacks and not Refreshes
You could set a hidden input with a nonce value generated randomly every time the form is loaded (but not on postback), then check if the nonce value got sent twice. If it got sent a second time, it was a refresh.
you could try like
protected void Button1_Click(object sender, EventArgs e)
{
//your code of Click event
//..............
//...............
// and then add this statement at the end
Response.Redirect(Request.RawUrl); // Can you test and let me know your findings
}
Sample working code for the accepted answer
Add this line in designer
<input type="hidden" runat="server" id="Tics1" value="GGG" />
Add following lined in the code behind
public partial class WebForm1 : System.Web.UI.Page
{
long tics = DateTime.Now.Ticks;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.Tics1.Value = tics.ToString();
Session["Tics"] = tics;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["Tics"] != null && Request["Tics1"] != null)
{
if (Session["Tics"].ToString().Equals((Request["Tics1"].ToString())))
{
Response.Write("Postback");
}
else
{
Response.Write("Refresh");
}
}
this.Tics1.Value = tics.ToString();
Session["Tics"] = tics;
}
}

Cookie only displayed on refresh?

I have some trouble understanding this one so here it is.
I'm trying to set a cookie and display the value on the page using ASP.NET + C#.
here's my code:
protected void lbChangeToSmall_Click(object sender, EventArgs e)
{
Response.Cookies["fontSize"].Value = "small";
}
and
<asp:LinkButton runat="server" id="lbChangeToSmall" Text="A" CssClass="txt-sm" OnClick="lbChangeToSmall_Click"></asp:LinkButton>
And finally
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write( Request.Cookies["fontSize"].Value);
}
}
When I click on the button, nothing is displayed on the page, but the cookie is actually set. If I refresh the page, the cookie displays.
So it seems that the cookie is set correctly but the application is not able to read it right away.
I tried to get rid of the if(postBack):
protected void Page_Load(object sender, EventArgs e)
{
Response.Write( Request.Cookies["virgilFontSize"].Value);
}
but it didn't change a thing.
What am I doing wrong?
Thanks!
The lblChangeToSmall_Click event is fired after the Page_Load event. Therefore the cookie write won't be available on the Request until the subsequent postback.
It will be avaialable on the client immediately though.
The first time, the request has no cookies (yet); it will only have them the second time around, after the response has set them. So your code has to deal with the possibility that Request.Cookies just may not have a "fontSize" entry, and provide the proper default when that is the case. For example:
HttpCookie cookie = Request.Cookies.Get("fontSize");
// Check if cookie exists in the current request.
if (cookie == null)
{
Response.Write( "Defaulting to 'small'.");
}
else
{
Response.Write( Request.Cookies["fontSize"].Value);
)

Categories