我需要允許用戶從收集用戶輸入的頁面重定向。如果用戶重定向,返回頁面時,表單應該填入用戶已經輸入的值。如何從字典鍵中恢復表單字段值
我完成了以下,但我猜測有一個更好的方法來做到這一點。
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");
}
}
任何幫助,將不勝感激。
在字典中KeyValuePair會工作的Cookie,但我的問題是你是如何保存字典的狀態..你可以看看使用Session對象和調查Session.Add方法..只是和Idea ..或Cookies ..?只要不保存大量的文本/數據,就可以查看隱藏字段或ViewState。我個人不會使用,如果我不需要..有Global.asax部分,你也可以使用/存儲會話變量..在處理Web時,我通常使用會話變量..但這只是我的個人選擇.. – MethodMan 2011-12-21 16:21:10
當你說'你如何拯救字典的狀態',你問我如何保存字典?如果是這樣,我將它保存到OnRedirectEvent()方法中的Session中 – Bengal 2011-12-21 16:30:50
我的意思是你通過ref傳遞該字典,因爲回發時該對象應該爲空,但是我個人會使用Session或Cookie Alans示例應該執行該操作。 – MethodMan 2011-12-21 16:33:20