2011-12-21 43 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