繁体   English   中英

如何从字典键中还原表单字段值

[英]How to Restore Form Field Values from Dictionary Keys

我需要允许用户从收集用户输入的页面重定向。 如果用户重定向,则在返回页面后,应使用用户已经输入的值填写表单。

我完成了以下工作,但我猜有更好的方法可以做到这一点。

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

任何帮助,将不胜感激。

假设数据库是不可能的,因为我们正在与一个匿名用户打交道-将字典放入会话中可能会占用服务器资源一些麻烦-除非您为会话运行单独的状态服务器或sqlserver。

将值保留在客户端cookie集合中将对匿名用户有效-尽管通过网络增加字节数。

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

记住要对Cookie进行HTML编码,以防Cookie在返回时被客户端脚本入侵

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM