Cookie only displayed on refresh? - c#

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);
)

Related

Remove Session Value If I Delete Value From Field And Re-Submit Form

I have an asp.net webform that stores details entered in the session and then displays all the details on a confirmation page later on. All these works are fine.
If the user navigates back to the page, the details are still displayed but the issue i'm having is that:
User Scenario
User enter's details in a none mandatory field and continues. This value is displayed on the confirmation page as expected. User then goes back to the page and deletes the value in the none mandatory field and continues BUT the value deleted is still deleted on my confirmation page.
I have debugged it and at first I can see that the field is empty. But when the code drops back into my submitbutton_click, it re-adds it.
The current code that I have is displayed below:
Code
protected void Page_Load(object sender, EventArgs e)
{
if (Step01AddressBuildingname.Text == string.Empty && Session["Step01AddressBuildingname"] != null)
{
Step01AddressBuildingname.Text = Session["Step01AddressBuildingname"].ToString();
}
}
protected void Step01SubmitButton_Click(object sender, EventArgs e)
{
Session["Step01AddressBuildingname"] = Step01AddressBuildingname.Text;
}
From what I can discern from your post it seems that when you update the Step01AddressBuildingname field to be blank and click on submit, this does not clear down the session value as expected. If so it's because you're not handling the post back in you page_load event. In asp.net webforms postbacks occur when a form is submitted to the server, in this scenario you just want to handle the form submission and not load the page as standard. You do this by checking the IsPostBack property on the page.
In your code, because you're not checking this property, tep01AddressBuildingname.Text = Session["Step01AddressBuildingname"].ToString(); is getting executed before the submit button's click event handler - hence the value doesn't get deleted. Try this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
if (Step01AddressBuildingname.Text == string.Empty && Session["Step01AddressBuildingname"] != null)
{
Step01AddressBuildingname.Text = Session["Step01AddressBuildingname"].ToString();
}
}
}
protected void Step01SubmitButton_Click(object sender, EventArgs e)
{
Session["Step01AddressBuildingname"] = Step01AddressBuildingname.Text;
}

Entering new cookie to save(also understanding cookies)

Right now I have made a registration form. I want a user to enter their name and have it save as a cookie. When they reload the website their information will still appear. As I currently have it coded that happens. However, if someone wants to enter new information they have to click my clear button. Is there anyway I can have it where if the user just types in a new name that it will automatically save that cookie and use the newest cookie that was typed. Here is some of my code
Also, to be a little bit more specific, I am wanting it where they can type in a name, register it, reload the page and the name appears, but if they type in a new name over that name and it register, that new name will appear. Right now they have to click clear before hitting register.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["FirstName"] != null)
{
TextBox1.Text = Request.Cookies["FirstName"].Value;
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Cookies["FirstName"].Value = TextBox1.Text;
Response.Cookies["FirstName"].Expires = DateTime.Now.AddDays(30);
}
Then the way I have them enter new information is the clear button (which I don't want)
protected void Button2_Click(object sender, EventArgs e)
{
DeleteCookie();
}
private void DeleteCookie()
{
HttpCookie cookie = new HttpCookie("FirstName");
cookie.Expires = DateTime.Now.AddSeconds(-1);
Response.Cookies.Add(cookie);
TextBox1.Text = "";
}
It doesn't appear you are including all the relevant code (as you aren't even adding the cookie to the response), but going with what you posted, your problem seems to be with not understanding the ASP.NET Lifecycle.
When they click your button, the Page_Load event is going to run first (before Button1_Click). So that means whatever they typed gets overwritten with the cookie value when the cookie exists... so yeah, they can never set a new value until the cookie gets deleted.
So fix this by only setting the value of TextBox1 when it isn't a post back:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Request.Cookies["FirstName"] != null)
{
TextBox1.Text = Request.Cookies["FirstName"].Value;
}
}
And your button click should look more like:
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["FirstName"];
if (c == null)
{
c = new HttpCookie("FirstName");
}
c.Value = TextBox1.Text;
c.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(c);
}
Another good thing to realize is that cookies can't really be trusted, as they can be edited by the user. Things like HttpOnly help (secure cookies -- over HTTPS -- are even better, but then you can only read the cookie over HTTPS, which can be problematic unless your entire site is secure), but for sensitive info I like to encrypt the data too... you don't want someone changing the name in the cookie to "Admin" and then getting free reign over your site (assuming that is how you are handling security).
You could use the TextChange event.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.textchanged(v=vs.110).aspx
Try:
<asp:TextBox runat="server" id="TextBox1" OnTextChanged="TextBox1_TextChanged" />
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
DeleteCookie();
}
I have never found the TextChanged event very intuitive for the end user because you still need a way for the end user to trigger a postback to get the event to fire.
There are many ways to have them trigger the postback for example OnBlur, pressing Enter, clicking a button. It all depends on what you want the user experience to be.
If it were my UI then I would probably have a hidden Save button that displays when they start typing in the TextBox via jQuery (or Javascript), when they finish typing they click the Save button to trigger the event.

asp.net cookie not saved

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
}

redirect page on specific user detection asp.net

i would like how to implement the following in asp.net:
i have windows authentication and i would like the server to detect who the user is and redirect the page depending on the username on the page.
is there an easy way to do this?
You can get the username like...
string username = HttpContext.Current.User.Identity.Name.ToString();
Once you have the username you can redirect the page to a specific page.
Edit: You can do it in Application_AuthenticateRequest event, that is Global.asax file
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
// put code here....
}
}
For event it depends of your code.
i supose you could do such a thing in the page_load event if you have any doubt you should check the ASP.NETlifecylce http://www.google.fr/search?sourceid=chrome&ie=UTF-8&q=asp.net+lifecycle
BTW you can use Response.redirect to redirect the user.
pretty straightforward
protected void Page_Load(object sender, EventArgs e)
{
string username = HttpContext.Current.User.Identity.Name.ToString();
if (username == "someusername")
{
Response.Redirect("someaspxfile.aspx");
}
}
If you are looking for picking up the control with username in it, it will be available in the request. You can pick the data from request

Session doesn't remember set value

I am trying to pass data between two pages using Session State in ASP.NET. The data that needs to be passed is from a GridView's Cell. So, on SelectedIndexChanged event I'm storing the data like that:
protected void GridViewEmployees_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Name"] =
this.GridViewEmployees.Rows[GridViewEmployees.SelectedIndex].DataItem;
}
And then, I want to use the Session's contents in another page. The code:
protected void Page_Load(object sender, EventArgs e)
{
string name = (string)(Session["Name"]);
string[] names = name.Split(' ');
this.EntityDataSourceNorthwind.Where =
"it.[FirstName] = \'" + names[0] +
"\' AND it.[lastName] = \'" + names[1] + "\'";
}
But I get a null reference exception. Also, I have set the Session initialization on the Page_Load event and there the Session is stored and everything works just fine. I mean:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Name"] == null)
{
Session["Name"] = "Andrew Fuller";
}
}
This is in the page which sends the information.
If you need more source or info, just write it down. It will be provided ASAP.
Thanks in advance!
This is actually not a problem with your Session. A row's DataItem is only available during the RowDataBound event. Set a break point in your GridViewEmployees_SelectedIndexChanged method, and check the value of the DataItem in your immediate window. It will be null.
The two most likely culprits are either - session state is disabled (EnableSessionState="false"), or cookies are disabled and you're not using cookieless sessions.

Categories