我一直在尝试使用泛型来存储会话中的数据。 它将有2个页面和1个类名人员来处理信息。
第1页默认页面允许用户输入名称并选择性别和日期。 我正在尝试将提交的内容存储到通用&会话带到第二页显示所有提交的用户数据。
DefaultPage
public partial class _Default : Page
{
Person p;
List<Person> Test;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Test = new List<Person>();
Session["carrytonext"] = Test;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Person p = new Person(TextBox1.Text, DropDownList1.SelectedValue, Calendar1.SelectedDate);
Label1.Text = p.PrintPerson();
Test = (List<Person>)Session["carrytonext"];
Test.Add(new Person(TextBox1.Text, DropDownList1.SelectedValue, Calendar1.SelectedDate));
}
}
这是我的班级:
public class Person
{
public string name;
private string gender;
private DateTime dob;
public string Name
{
get
{return name;}
set
{name = value;}
}
public string Gender
{
get
{return gender;}
set
{gender = value;}
}
public DateTime Dob
{
get
{return dob;}
set
{dob = value;}
}
public Person(string name, string gender, DateTime dob)
{
this.name = name;
this.gender = gender;
this.dob = dob;
}
public string PrintPerson()
{
string s;
s = "Hello, my name is " + name + ". I'm " + gender + ". My DOB is " + dob.ToShortDateString() + "\n\n";
return s;
}
}
在我的第二页:
protected void Page_Load(object sender, EventArgs e)
{
foreach (var inputstring in Test)
{
ListBox1.Items.Add(inputstring + "");
}
}
答案 0 :(得分:1)
您必须再次从测试列表设置会话:
第1页
protected void Button1_Click(object sender, EventArgs e)
{
Person p = new Person(TextBox1.Text, DropDownList1.SelectedValue, Calendar1.SelectedDate);
Label1.Text = p.PrintPerson();
Test = (List<Person>)Session["carrytonext"];
Test.Add(new Person(TextBox1.Text, DropDownList1.SelectedValue, Calendar1.SelectedDate));
// Add this line to your code
Session["carrytonext"] = Test;
}
第2页
protected void Page_Load(object sender, EventArgs e)
{
List<Person> test = (List<Person>)Session["carrytonext"];
foreach (var inputstring in Test)
{
// change here
ListBox1.Items.Add(inputstring.PrintPerson()+" ");
}
}