Redirecting page depending on query string
I have page A, B and C. In the page load of C, i have used a query string parameter to display some tables depending on where it came from, either A or B. Page C has Cancel button. When a user clicks Cancel, it has to check where it came from and should redirect开发者_如何学编程 to same page, i mean either A or B. I am not at all sure how to use query string for redirecting.
Please help me out!!
Thanks!
You can use something like this to redirect base on the querystring:
var pageToredirectTo = "default.aspx";
switch(Request.QueryString["param"]) {
case "a":
pageToredirectTo = "pageA.aspx";
break;
case "b":
pageToredirectTo = "pageB.aspx";
break;
}
Response.Redirect(pageToRedirectTo);
As a good practice it's better to create properties on the page to save the values of query strings in ViewState in order to make it safe for future use and to prevent unexpected behaviors of hackers. The following code is not for your situation exactly but -if you want how to use query strings well- it's for values passed using query strings to specify which data will be displayed on the a page and this page has many buttons that make many postbacks of the page and finally you will redirect the user to another page based on the value of a query string.
public class Default : Page
{
private readonly string VS_Bool_FromPageA = "VS_Bool_FromPageA";
protected void Page_Load(object sender,EventArgs e)
{
if(!IsPostBack)
{
if(!string.IsNullOrEmpty(Request["frompageA"])
{
bool fromA;
if(bool.TryParse(Request["frompageA"],out fromA) && fromA)
FromPageA = true;
else
FromPageA = false;
}
}
}
private bool FromPageA
{
get
{
if (ViewState[VS_Bool_FromPageA] != null)
{
return (bool)ViewState[VS_Bool_FromPageA];
}
else
return false;
}
set
{
ViewState[VS_Bool_FromPageA] = value;
}
}
//if the user changed the value of the query string before hitting the cancel button
//your logic will stay consistent
protected void buttonCancel_Click(object sender,EventArgs e)
{
if(FromPageA)
Response.Redirect("~/pagea.aspx");
else
Response.Redirect("~/pageb.aspx");
}
}
精彩评论