问题
I have a web form in .NET using ASP and C#. This form has a DropDownList control with its AutoPostBack property set to True.
Some data on the form is displayed when the user selects an item from the DropDownList.
Now, I want the user to be able to share his or her data by just copying the URL which has the QueryString on it like http://www.site.com?ProdID=1234
.
I have done the following to try to accomplish this:
protected void Page_Load(object sender, EventArgs e)
{
// check if the URL has a QueryString item if yes the use it.
if (!String.IsNullOrEmpty(Request.QueryString["ProdID"]))
{
ddlProduct.SelectedIndex = ddlProduct.Items.IndexOf(ddlProduct.Items.FindByValue(Request.QueryString["ProdID"]));
}
}
The Problem with this code is that when the user chooses a different item from the DropDownList his or her selected item gets overwritten by the Page_Load() since we have now a QueryString on the URL. (I build the QueryString and then use the Redirect() method to the same page on an Event)
So my question here is: Is it possible to keep changing the URL's query string on the fly when the user changes the selected item from the DropDownList and display the proper data on the form for the selected item?
I have the feeling that this is like the chicken or the egg problem.
Thank you.
回答1:
Check for whether or not the page is posting back to the server, along with your existing logic, like this:
if(!IsPostBack && !String.IsNullOrEmpty(Request.QueryString["ProdID"]))
{
ddlProduct.SelectedIndex = ddlProduct.Items.IndexOf(ddlProduct.Items.FindByValue(Request.QueryString["ProdID"]));
}
来源:https://stackoverflow.com/questions/19987952/how-to-properly-use-a-querystring-in-net-asp-c