我试图从一个页面中的文本框中获取变量,然后传递它们以显示在另一个页面中。好像我应该使用会话(因为那是这个任务的主题)。注释掉的代码是我尝试过的各种方法都没有用。
在首页上:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}
//This is a button link that sends to the next page, "Results"
protected void cbtnlSubmit_Click(object sender, EventArgs e)
{
string sName = "";
int sSize = 0;
string sTopping = "";
decimal sPrice = 0M;
if (IsPostBack)
{
Validate();
if (IsValid)
{
sName = ctbName.Text;
sSize = Convert.ToInt32(ctbSize.Text);
sTopping = ctbTopping.Text;
sPrice = Convert.ToDecimal(ctbPrice.Text);
if (string.IsNullOrEmpty(sTopping) == true)
{
sTopping = "cheese";
}
/* DOESN'T WORK
Session.Add(sName, sSize);
Session.Add(sTopping, sPrice);
Server.Transfer("Results.aspx");
*/
/*DOESN'T WORK
Session["pizza"] = new Pizza()
{
name = sName,
size = sSize,
topping = sTopping,
price = sPrice
};
*/
//ALSO DOESN'T WORK
Session["name"] = sName;
Session["size"] = sSize;
Session["topping"] = sTopping;
Session["price"] = sPrice;
Response.Redirect("Results.aspx");
}
}
}
}
这是"结果"应显示变量的页面
public partial class Results : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count != 0)
{
lblName.Text = Session["name"].ToString();
string size = Session["size"].ToString();
string topping = Session["topping"].ToString();
string price = Session["price"].ToString();
string pizzaInfo = (size + " inch pizza with " + topping + " for $" + price.ToString());
lblPizzaInfo.Text = pizzaInfo;
/*
string name = Session.Keys[0];
int size = Convert.ToInt32(Session[name]);
string topping = Session.Keys[1];
decimal price = Convert.ToDecimal(Session[topping]);
string pizzaInfo = (size.ToString() + " inch pizza with " + topping + " for $" + price.ToString());
lblName.Text = name;
lblPizzaInfo.Text = pizzaInfo;
*/
}
lblName.Text = "Meaghan";
}
}
两个页面都显示。在辅助页面末尾设置的lblName.Text是一个测试,以确保标签可见(它们是),但没有信息传递到辅助页面。只有当我把它放在if语句之外时才会显示该标签; if语句执行中没有任何内容。我已经尝试阅读推荐的问题并发现我应该启用" sessionState",这是我为两个页面所做的,但该程序仍然无法正常工作。
我在属性中选择了EnableSessionState为True,它表示EnableSessionState =" True"在aspx文件的顶部。我添加到web.config文件中。所以我猜会话状态模式是" InProc"模式?
我尝试添加会话[" test"] =" Hello"进入Default页面,将Response.Write(Session [" test"])放入Results页面。现在它在lblName.Text = Session [" name"]。ToString()[在if语句中]抛出NullReferenceException。
答案 0 :(得分:0)
您项目的根目录Web.config
中需要以下内容:
<sessionState mode="InProc" cookieless="false" timeout="10" />
如果您的配置文件中有此条目,可否请确认?
它应位于
下<configuratio>
<system.Web>
有关sessionState
的更多信息:https://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.71).aspx