Preserving DropDownList settings - c#

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

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

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.

How can I trigger dropdown while viewing asp.net page

There are two Dropdown in the asp.net page.
When I select first one (city), the second one (district) is triggered.
I have a save button for the page.
When I click the save button, I write the SelectedValues of dropdowns in to the database.
And when I open the page again, I assign the values to the dropdown's selected values.
The first one is ok when I assign dropdown.SelectedValue = "5" but the second one is not triggered. How can I trigger it?
Thanx.
I have done the same thing. Suppose you have drop down say ddlCountry and ddlCity. You need to load all cities just for the selected country.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LoadCountriesInDropDown(ddlCountry);
ddlCountry.SelectedValue = "5" //For eg:
LoadCitiesByCountrySelected(ddlCity, ddlCountry.SelectedValue); // selected country value was set here as 5
ddlCountry_SelectedIndexChanged(null, null);
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddlCountry.SelectedItem.Text == "Select")
{
ddlCity.Items.Clear();
}
else
{
LoadCitiesByCountrySelected(ddlCity, ddlCountry.SelectedValue);
}
}
Hope this was what you wanted.

Checking Page.IsPostBack in user controls

Is it recommended to check the Page.IsPostBack in a user control Page_Load Event like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
I am getting wierd results
Edit ~ Here is the thing. When the main form is loaded, I use Request.QueryString to get the customer id which I then place in a SESSION variable.
On the control Load event I read the SESSION variable to get the data for that customer. So, do I need to check PostBack at the control level?
Edit ~ Here is the load event of the control
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Getting and storing the customer account number
if (string.IsNullOrEmpty((string)Session["CustomerNumber"]))
{
Session["CustomerNumber"] = cust.GetCustomerNumber(myHelper.GetCustomerIDFromQueryString());
LoadProductData();
}
}
}
Here is the myHelper Class
static class myHelper
{
public static Guid GetCustomerIDFromQueryString()
{
//Getting the GUID (used as customerid in CRM) from the URL request of the selected account.
return Sql.ToGuid(System.Web.HttpContext.Current.Request["ID"]);
}
}
}
If you use "!IsPostBack" in page load, when the user click other control it do a postBack, so you don't get your data.
I hope that helps you.
Just checking it for no reason? Absolutely not. If you should do something only on first load and not on subsequent post backs then it's the pattern that should be used.
Are you sure that you will always have a "CustomerNumber" already stored in the Session by the time you get to your page? Is there any rhyme or reason that you can find as to when you get data and when you don't?

Categories