从aspx页面的会话中获取数据?

时间:2015-03-24 10:23:30

标签: c# asp.net session

我有班级豆, 然后我创建了一些关闭Bean的ob并将它们添加到列表中,然后我将列表转换为数组。 我将此数组添加到会话中并在aspx页面中使用它,但无法从会话中获取数据。

public Bean[] listAnswer()
    {
        SqlConnection con = new SqlConnection(@"Data Source=LEHUULOC-PC;Initial Catalog=WebThiTracNghiem;Integrated Security=True");
        con.Open();
        string sql = "SELECT * FROM tblCauhoi";
        SqlCommand com = new SqlCommand(sql, con);
        com.CommandType = CommandType.Text;
        SqlDataReader dr = com.ExecuteReader();
        List<Bean> Listbean = new List<Bean>();

        Bean[] result = null;
        while (dr.Read())
        {
            string macauhoi = (string)dr[0];
            string cauhoi = (string)dr[1];
            string cautraloi = (string)dr[2];
            string traloidung = (string)dr[3];
            //string dokho = (string)dr[4];
            Bean answer = new Bean(macauhoi, cauhoi, cautraloi, traloidung, "");
            Listbean.Add(answer);
            result = new Bean[Listbean.Count];
            result = Listbean.ToArray();
        }
        dr.Close();
        con.Close();
        return result;
    }

======================================

Bean bean = new Bean();
Bean[] answer = bean.listAnswer();
Session.Add("ANSWER",(Bean[])answer);

======================================

<body>
<form id="form1" runat="server">
<div>
this is hocsinh page
    <asp:Label ID="lblWelcome" runat="server"></asp:Label>
    <%  

        foreach (var Bean in Session["ANSWER"])
        {
        }
    %>
</div>
</form>

但是我收到错误:foreach语句不能对'object'类型的变量进行操作,因为'object'不包含'GetEnumerator'的公共定义

2 个答案:

答案 0 :(得分:0)

试试这个:

<%  
    Bean[] list = (Bean[])Session["RESULT"];
    if (list != null)
        foreach (var Bean in list)
        {
        }
%>

答案 1 :(得分:0)

Bean必须是可序列化的,并将它像这样放入你的会话中:

Session.Add("ANSWER",bean);

这样读:

var beans = Session["Answer"] as Bean[];