.NET method with puzzling behaviour
I have a method that works in mysterious ways.
Running this works fine;
FindConcept("Product");
Running this produces an (unwanted) different result, even though the value of SelCatID is "Product";
FindConcept(SelectedCategoryID);
Where the SelectedCategoryID looks like:
protected string SelectedCategoryID
{
get
{
if (Request["c"] != null)
{
string c = Request["c"];
ViewState["SelectedCategoryID"] = c;
return c;
}
if (ViewS开发者_C百科tate["SelectedCategoryID"] != null)
{
string cid = ViewState["SelectedCategoryID"] as string;
if (!string.IsNullOrEmpty(cid))
{
return cid;
}
return "";
}
else
return "";
}
}
This leads me to believe that there must be some weird side-effect in the get-method of the SelectedCategoryID object. I am new to .NET , so I don't have a good idea of how ViewState works.
I've tried debugging this in numerous way, for example I've tried this:
System.Diagnostics.Debug.WriteLine(SelectedCategoryID);
FindConcept(SelectedCategoryID);
Where the debug.writeline will produce "Product", which should mean FindConcept behaves as expected.
This has left me completely puzzled. How should I continue to tackle this problem?
ViewState in ASP.NET webforms is written out to the html as a hidden form field (encoded, and typically encrypted).
This means that viewstate will be available on postback requests, but not be available across an http redirect.
In the code above, it looks like the code is trying to handle both post backs and other types of requests - because it uses the indexer for the Response property which
Gets the specified object in the Cookies, Form, QueryString or ServerVariables http://msdn.microsoft.com/en-us/library/system.web.httprequest.item%28VS.71%29.aspx
One likely scenario is that you are redirecting without passing along the information using one of the above methods, which means view state is not available, and the information is also not available in the url query string or cookie etc.
Edited - Example
There are many ways this could look, here is a simple example: For example, suppose on one page you retrieve the "SelectedCategoryID" from the database in a GridView. Under default scenarios, this would be stored in the Gridview of the page, and would be available in the viewstate when posting back to the same page (see http://www.xefteri.com/articles/show.cfm?id=18 and http://msdn.microsoft.com/en-us/library/ms972976.aspx).
However, suppose on a button click you did something in response to a button click such as
Response.Redirect("SomeOtherPage.aspx")
In this case, the ViewState on "SomeOtherPage.aspx" will not hold the value, so your getter is going to look for the value in other places, such as the url. In this case, you could pass the "SelectedCategorID" along with something such as
Response.Redirect("SomeOtherPage.aspx?c=" + HttpUtility.UrlEncode(selectedCategoryId));
精彩评论