Entering new cookie to save(also understanding cookies) - c#

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.

Related

Make a field read only based on value in ASP.net: C#, ASP.Net

Everyone that has responded to my questions have been so very helpful and I am closing in on finishing this app. My challenge now is to make 3 fields read only based on a login.
I have the following code that does exactly what I need and assign the currently logged in user to a text field. What I want to do is make some other text fields (Read Only) if the login user does not equal a specific value. For example, if submitted_by_email_username does not equal administrator1#samplecompany.com then make the text field (Salary_in) which is a textbox, Read Only. I can read code much than I write it these days so I apologize if this is a simple request. I would like to make three fields Read Only based on that logic in the COde Behind.
protected void Page_PreInit(object sender, EventArgs e)
{
if (submitted_by_email_username != null)
{
_ = Context.User.Identity.Name;
if (User.Identity.IsAuthenticated)
submitted_by_email_username.Text = User.Identity.Name;
}
}
First of all, you don't need code in Page_PreInit 99.9% of the time in webforms. Even with dynamic controls you would only need Page_Load.
But you can make a TextBox readonly by using the Enabled property.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
submitted_by_email_username.Enabled = false;
submitted_by_email_username.Text = User.Identity.Name;
}
}

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

Is there some way to go on the previous page get the pressed button text?

I'm working on Visual Studio, in C# language
I would like to ask if there's someway to go back to get the ButtonX.Text I pressed on the previous page, some sort of Login without a password.
Basically I need a worker to specify which person he is by clicking on their name (button) then it goes foward to the next page I have a label on the MasterPage but it resets everytime it goes on a next page what I would like to do is keep the info there
If you need some code tell me.
Thanks
You could use session variables?
On the button click handler on the first page...
protected void button_Click(object sender, EventArgs e)
{
Session["Worker"] = button.Text;
}
Then on the second page...
Label.Text = Session["Worker"];
Based-off your reply to Zollistic's answer, you could do this...
Apply this event to all your all your worker buttons...
protected void button_Click(object sender, EventArgs e)
{
if (Session["Worker"] == null) Session["Worker"] = "";
Session["Worker"] += button.Text + ",";
}
Now Session["Worker"] has a character-delimited list of all the clicked buttons. The character in this example is a comma; but you can change it to whatever you want (i.e. a pipe "|").

Preserving DropDownList settings

I have a webpage: Menu.aspx, where I have the following controls of relevance:
a DropDownList with some values
a button, which redirects me to a page called Edit.aspx.
In my Edit.aspx page, I have a cancel button, which redirects the user back to the Menu page with the following C# method
protected void btnCancel_click(object sender, EventArgs e)
{
Response.Redirect("Menu.aspx");
}
What I would like to do is when I redirect my user back to Menu.aspx, I preserve the value of the DropDownList that they selected.
Thanks in advance!
EDIT: Ideally, I want to achieve this without a QueryString (if Possible)
EDIT2: I was thinking of something invovling a viewstate or postback but I'm unfamiliar with those.
When you called Response.Redirect("Menu.aspx"); you were already making a new request which the previous page was not part. It's like calling the page anew.
You can put the value in session before coming to Edit.aspx or pass the value back through query string
Response.Redirect("Menu.aspx?dropdownvalue=123");
On Menu.aspx, you'll check if ?dropdownvalue=123 exist and you set selected item to that value
Isn't the most ellegant solution, but you can create a session variable containing the selected value.
For example:
dropDown_SelectedIndex(object sender, EventArgs e)
{
Session["SelectedItem"] = dropDown.SelectedValue;
}
When you do the redirect, on the page load of the Menu.aspx, after you populate the DropDown, check if this session variable exists, then select the item and remove it from the application.
void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//populate drop down here
if(Session["SelectedItem"] != null)
{
dropDown.SelectedValue = Session["SelectedItem"].ToString();
Session["SelectedItem"] = null;
}
}
}
Or you can pass it via query string, but this way you preserve you url

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