I need to allow a user to redirect from a page that collects user input. Should the user redirect, upon return to the page the form should be filled in with the values that the user had already entered.
I completed the following but I’m guessing there is a better way to do this.
On RedirectEvent()
{
Dictionary<string, string> form = new Dictionary<string, string>();
foreach (string key in Request.Form.AllKeys)
{
if (key != null)
form.Add(key, Request.Form[key]);
}
Session["requestFormKeys"] = form;
Response.Redirect(url);
}
On Page_Load(object sender, EventArgs e)
{
if (Session["requestFormKeys"] != null)
{
Dictionary<string, string> form = Session["requestFormKeys"] as Dictionary<string, string>;
// I tried using 'Request.Form.AllKeys' here but it was always null
foreach (KeyValuePair<string, string>pair in form)
{
// cannot use a switch because switch requires a constant (value must be known at compile time)
if (pair.Key.Contains("txtName"))
txtName.Text = lblNameView.Text = pair.Value;
else if (pair.Key.Contains("ddlType"))
ddlType.SelectedValue = pair.Value;
else if (pair.Key.Contains("ddlPriority"))
ddlPriority.SelectedValue = pair.Value;
.
.
.
//this is a tedious process and should be streamlined
.
.
.
else if (pair.Key.Contains("txtDateStart"))
txtDateStart.Text = pair.Value;
else if (pair.Key.Contains("txtDateEnd"))
txtDateEnd.Text = pair.Value;
}
}
Session.Remove("requestFormKeys");
}
}
Any help would be appreciated.
Assuming a database is out of the question because we are dealing with an anonymous user – putting the dictionary in the Session could be a little heavy on server resources – unless you run a separate stateserver or sqlserver for the session.
Persisting the values in a client side cookie collection would work for an anonymous user – though increase bytes over the wire.
Remember to HTML encode the cookie in case the cookie has been hacked with client-side script on the way back