在另一个页面中访问会话变量 [英] accessing session variable in another page

查看:85
本文介绍了在另一个页面中访问会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET中的Hello..im新手.使用会话,我想将一页的变量访问到另一页中,我该怎么做.这是我正在尝试的不起作用的

hello guys..im newbie in ASP.NET. Using Session, i want to access variable of one page into another how do I do that. Here is what I am trying which is not working

public class Student{
   string name;
   string Class;

   public Student(string n, string c){
       name = n;
       class = c;
   }
}


现在,在Default.aspx.cs的Page_Load()事件中,创建两个Student对象并将其添加到Session中(以及这样的ListBox中)


Now in the Page_Load() event of Default.aspx.cs im creating two objects of Student and adding them to the Session (and to the ListBox like this)

Student student1 = new Student("Muzammil","MS");
Student student2 = new Student("Ali","MBA");

//adding these objects to Session
Session["std1"] = student1;
Session["std2"] = student2;

//adding these objects'' name to list box
list1.Items.Add(student1.name);
list1.Items.Add(student2.name);


现在,在Default.aspx.cs中的按钮事件中,我按如下方式访问它们


Now in the button''s event in Default.aspx.cs im accessing these as follows

int index = list1.SelectedIndex;
Student std = (Student)Session[index];

lblRecords.Text = "Name:  " + std.name;
lblRecords.Text = "Class:  " + std.Class;


现在,还有另一个页面"Page1.aspx",上面带有标签.如何在标签上访问这些变量? thnx


Now there is another page "Page1.aspx" with a label on it. How do I access these variable on that label? thnx

推荐答案

如果有人访问Page1.aspx页面1st,则无法在会话中获取该值.因此,您应该检查1st会话中的值是否可用.

if(Session ["std1"]!= null && Session ["std2"]!= null)
{
学生std1 =学生的Session ["std1"];
学生std2 =学生的Session ["std2"];
}
If any one visit Page1.aspx page 1st then you can not get the value in session. So, you should check 1st that values are available in the session.

if (Session["std1"] != null && Session["std2"] != null)
{
Student std1 = Session["std1"] as Student;
Student std2 = Session["std2"] as Student;
}


数据以键,值格式存储在会话中.正如您已经在做的那样.

要访问任何特定数据,您必须知道密钥.

因此,在任何页面上,您都可以按以下方式访问数据:
Data is stored in session in Key, Value format. As you are doing already.

To acces any particular data, you must know the key.

So on any page, you can access the data as
Student student1 = (Student)Session["std1"];
Student student2 = (Student)Session["std2"];


我建​​议您通过
获取选定的列表索引 列表<> stu_list =(列表)previousPage.findControl(");
然后获取其选定的索引并获取会话值.
I would suggest you to get the selected Index of list by
List<> stu_list = (List) previousPage.findControl("");
then take its selected index and get the session value.


这篇关于在另一个页面中访问会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆