如何将这两个变量的值传递给ShowFooBar
点击事件?
当我运行下面的代码时,变量在write语句中没有值。
public partial class _Default : System.Web.UI.Page
{
string foo = String.Empty;
string bar = String.Empty;
protected void Submit_Click(object sender, EventArgs e)
{
if (SomeCondition(x,y))
{
foo = "apple";
bar = "orange";
}
}
protected void ShowFooBar_Click(object sender, EventArgs e)
{
Response.Write("foo=" + foo + "& bar=" + bar);
}
}
答案 0 :(得分:2)
Web表单是无状态的,这意味着每次回发到其中一个点击事件时,都会从_Default类创建一个新的页面对象,其中foo和bar被实例化为空字符串,因此ShowFooBar_Click事件将显示。
如果您希望在请求之间保留foo和bar的值,则必须将它们存储在某处并在事件请求期间检索它们。根据您的需要提供各种选项,例如Session,ViewState,隐藏字段等。例如:
protected void Submit_Click(object sender, EventArgs e)
{
if (SomeCondition(x,y))
{
ViewState["foo"] = "apple";
ViewState["bar"] = "orange";
}
}
protected void ShowFooBar_Click(object sender, EventArgs e)
{
if(ViewState["foo"] != null && ViewState["bar"] != null)
{
Response.Write("foo=" + ViewState["foo"] + "& bar=" + ViewState["bar"]);
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
public partial class _Default : System.Web.UI.Page
{
protected void Submit_Click(object sender, EventArgs e)
{
if (SomeCondition(x, y))
{
ViewState["foo"] = "apple";
ViewState["bar"] = "orange";
}
}
protected void ShowFooBar_Click(object sender, EventArgs e)
{
Response.Write("foo=" + ViewState["foo"].ToString() + "& bar=" + ViewState["bar"].ToString());
}
}