简体   繁体   English

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

[英]get data from session in an aspx page?

I have class Bean, then I creat some ob off Bean and add them to a list, then I convert list to an array. 我有Bean类,然后在Bean上创建了一些对象并将其添加到列表中,然后将列表转换为数组。 I add this array into a session and use it in a aspx page, but cannot get data from session. 我将此数组添加到会话中并在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>

but I receive error: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator' 但我收到错误消息:foreach语句无法对类型为“对象”的变量进行操作,因为“对象”不包含“ GetEnumerator”的公共定义

Try this: 尝试这个:

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

Bean has to be serializable and put it like this into your session: Bean必须是可序列化的,并将其像这样放入您的会话中:

Session.Add("ANSWER",bean);

read it like this: 像这样阅读:

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

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

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