Datos de sesión global en línea de ASP.NET

I am unable to figure out how to store a List of strings as a global variable, add to that list on button click for any unknown number of times, store that list in a session, and then properly access that session data in a separate page. I have gotten close, but have weird things occurring and my efforts to debug are doing even more unusual things.

Here is the first page script with Button1_Click() bound to OnClick of Button1:

<%@ Page Language="C#" Debug="true"  %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Drawing" %>


<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8"/>
    <title></title>    

    <script type="text/javascript">
        function validateNums(ele, evt)
        {
            var charCode = (evt.which) ? evt.which : event.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                if (ele.id == 'TextBox1') {
                    var i = document.getElementById('TextBox1').value;
                    document.getElementById('TextBox1').value = i.slice(0, -1);
                }
                else
                {
                    var b = document.getElementById('TextBox2').value;
                    document.getElementById('TextBox2').value = b.slice(0, -1);
                }
            }
        }
    </script>

    <script runat="server">
       private static int counter = 0;
       List<string> reg = new List<string>();

        protected void Page_Load(object sender, EventArgs e) 
        {
            string[] states = { "AK","AL","AR","AS","AZ","CA","CO","CT","DC","DE","FL","GA","GU","HI","IA","ID",
            "IL","IN","KS","KY","LA","MA","MD","ME","MH","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ","NM","NV","NY",
            "OH","OK","OR","PA","PR","PW","RI","SC","SD","TN","TX","UT","VA","VI","VT","WA","WI","WV","WY" };

            int b = 0;

            foreach (string i in states) 
            { 
            this.DropDownList1.Items.Add(states[b]);
            b++;
            }

            if (Session["counter"] != null)
            {
                Session.Clear();
            }
            else { counter = 0; }

        }

        protected void Page_Unload(object sender, EventArgs e) 
        {
            Session["counter"] = counter;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (TextBox1.Text.Length == 0) Alert_First();
            if (TextBox2.Text.Length == 0) Alert_Second();
            if (DropDownList1.SelectedValue == "") Alert_State();
            if (TextBox4.Text.Length == 0) Alert_Password();
            if (TextBox1.Text.Length != 0 && TextBox2.Text.Length != 0 && DropDownList1.SelectedValue != "")
            {
                if (Password_Validate()) Save_Registery();
                else Alert_Password();
            }
        }

        private bool Password_Validate() 
        {
            foreach (char i in TextBox4.Text)
            {
                if (char.IsNumber(i))
                    return true;
            }
            return false;
        }

        private void Alert_First() 
        {
            TextBox1.BackColor = Color.Red;
            TextBox1.Text = "A value is required";
        }
        private void Alert_Second()
        {
            TextBox2.BackColor = Color.Red;
            TextBox2.Text = "A value is required";
        }
        private void Alert_State()
        {
            DropDownList1.BackColor = Color.Red;
        }
        private void Alert_Password()
        {
            TextBox4.BackColor = Color.Red;
            TextBox4.Text = "A value is required with at least one numeric value";
        }
        private void Save_Registery() 
        {
           if (Session["regList"] != null)
            {
            reg.AddRange((List<string>)Session["regList"]);
             }
            reg.Add(TextBox1.Text);
            reg.Add(TextBox2.Text);
            reg.Add(DropDownList1.Text);
            reg.Add(TextBox4.Text);
            Session["regList"] = reg;
            TextBox3.Text = counter.ToString();
            counter++;
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            int count = 0;

            foreach(string i in reg)
               {
                       TextBox3.Text = TextBox3.Text + reg[0].ToString();
                       count++;
               }
        }

</script>

</head>

<body style="margin:auto; max-width:300px;">
    <form id="form1" runat="server">
    <div style="float:left; max-width:200px;" >
        <asp:Label ID="Label1" runat="server" Text="First Name: "></asp:Label><br />
        <asp:TextBox ID="TextBox1" runat="server"  ></asp:TextBox>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Last Name: "></asp:Label>
        <br /> 
        <asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
        <asp:Label ID="Label3" runat="server" Text="State"></asp:Label>
        <br /> 
        <asp:DropDownList ID="DropDownList1" runat="server">
          <asp:ListItem Value="" Text=""></asp:ListItem>
        </asp:DropDownList>
        <br />
        <asp:Label ID="Label4" runat="server" Text="Password: "></asp:Label>
        <br />
        <asp:TextBox ID="TextBox4" runat="server" ></asp:TextBox> 
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"  />
        <asp:Label ID="Label5" runat="server" Text="All Fields are Required" Visible="false"></asp:Label>
        <asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine"></asp:TextBox>
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />
        <asp:HiddenField ID="HiddenField1" runat="server" />
    </div>
 <a href="Results.aspx" style="">
        <div>
            <p>
            Results
            </p>
        </div>
</a>
    </form>
</body>
</html>

And here is the second page:

<%@ Page Language="C#" Debug="true" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script runat="server">

        protected void Page_Load(object sender, EventArgs e) 
        {
            int counter = Convert.ToInt16(Session["counter"]);
            Repeater1.DataSource = (List<string>)Session["regList"];
            Repeater1.DataBind();
        }

    </script>

<meta charset="utf-8" />
    <title></title>    
</head>
<body>
    <form id="form1" runat="server">   
        <div>
            <%= Session["counter"] %>
        </div>
        <asp:Repeater ID="Repeater1" runat="server">
            <HeaderTemplate>
                <table>

            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <%# Container.DataItem %>
                    </td>


                </tr>

            </ItemTemplate>

            <FooterTemplate>
            </table>
            </FooterTemplate>

        </asp:Repeater>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </form>
</body>
</html>

This outputs only the LAST set of data that I entered via the previous page. The count I added to help debug tells me that there is only 3 values in my session variable of "regList". My question is why is my data getting overwritten every time the Button1_Click() is fired?

preguntado el 26 de septiembre de 13 a las 23:09

1 Respuestas

In the pageload event of the first page, you are resetting the seesion list by reg,

Session["regList"] = reg;

which by that time the reg is an empty list, and it becomes an issue

Respondido el 27 de Septiembre de 13 a las 00:09

yo añadí reg.AddRange((List<string>)Session["regList"]); to the beginning of Button1_Click and Session["regList"] = reg; to be the last thing executed in the method. It is still only storing the last 3 entries. - Justin

Have you tried debugging the code and see if everything is what you expected. Also, can you post your updated code there? - Mantente tonto

Also, how do you 'jump' from the first page to the second one? by another button click or just open that in another tab of the browser or ...? - Mantente tonto

I replaced the original code with my current files. Thanks for taking the time to look at it. As far as debugging see my post aquí on why I am having difficulty with this. - Justin

in your pageload event of the first page, you set the Session["regList"] = reg; by that time reg is an empty list, that is why it is getting reset everytime. You shouldn't do that if you want to keep a history of the reg. - Mantente tonto

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.