2011-12-21 40 views
1

我需要允許用戶從收集用戶輸入的頁面重定向。如果用戶重定向,返回頁面時,表單應該填入用戶已經輸入的值。如何從字典鍵中恢復表單字段值

我完成了以下,但我猜測有一個更好的方法來做到這一點。

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"); 
    } 
} 

任何幫助,將不勝感激。

+0

在字典中KeyValuePair會工作的Cookie,但我的問題是你是如何保存字典的狀態..你可以看看使用Session對象和調查Session.Add方法..只是和Idea ..或Cookies ..?只要不保存大量的文本/數據,就可以查看隱藏字段或ViewState。我個人不會使用,如果我不需要..有Global.asax部分,你也可以使用/存儲會話變量..在處理Web時,我通常使用會話變量..但這只是我的個人選擇.. – MethodMan 2011-12-21 16:21:10

+0

當你說'你如何拯救字典的狀態',你問我如何保存字典?如果是這樣,我將它保存到OnRedirectEvent()方法中的Session中 – Bengal 2011-12-21 16:30:50

+0

我的意思是你通過ref傳遞該字典,因爲回發時該對象應該爲空,但是我個人會使用Session或Cookie Alans示例應該執行該操作。 – MethodMan 2011-12-21 16:33:20

回答

1

假設數據庫不存在問題,因爲我們正在處理匿名用戶 - 將字典放在會話中可能會對服務器資源造成一些負擔 - 除非您爲會話運行單獨的狀態服務器或sqlserver。

堅持客戶端cookie集合中的值對匿名用戶有效 - 儘管通過網絡增加了字節數。

Response.Cookies["mypage"]["textbox1"] = textbox1.Text; 
Response.Cookies["mypage"]["textbox2"] = textbox2.Text; 

記住HTML編碼的情況下,該Cookie已經被黑客入侵與客戶端腳本在回來的路上

if (Request.Cookies["mypage"] != null) 
textbox1.Text = Server.HtmlEncode(Request.Cookies["mypage"]["textbox1"].Value); 
+0

這是一個好主意,但我主要以後是有沒有辦法避免手動填寫每個字段的值。也就是說,像迭代表單中的所有字段並從字典(或cookie)設置它們的值。我嘗試了Request.Form.AllKeys,但返回表單後,它始終爲Page_Load中的空值 – Bengal 2011-12-21 16:36:57

+0

您是否可以不迭代控件集合 - 出去並返回 - 儘管您必須將Control從Control轉換爲特定的Control類型拉/設置值。 – 2011-12-21 16:43:10

+0

我最終通過@Alan建議迭代了控件。感謝所有的反饋。我不得不向下鑽取到HtmlDataTable> HtmlDataRow> HtmlDataCell中以獲取我需要的控件(向下鑽取意味着嵌套的foreach循環) – Bengal 2011-12-21 21:25:21