我的Page_Load
事件中的代码有条件地设置了Session[]
变量,然后在该代码之后使用该变量的值将HTML
注入页面。它工作正常,但我想移动HTML
生成代码以在控件'事件之后运行,因为我有一个也可以影响此变量的按钮。所以我将第二部分移到了Page_PreRender
函数,它停止了工作。
这是有效的代码。它甚至在"Good"
事件中添加了标签PreRender
,这意味着Session[]
变量工作正常:
protected void Page_Load(object sender, EventArgs e)
{
using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
{
var response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
Session["loginId"] = response.ClaimedIdentifier;
break;
}
}
}
if (Session["loginId"] != null)
{
Label l = new Label();
l.Text = "Welcome " + Session["loginId"];
loginPH.Controls.Add(l);
Button b = new Button();
b.Text = "Logout";
b.Click += new EventHandler(logout_Click);
loginPH.Controls.Add(b);
}
else
{
Button b = new Button();
b.Text = "Log in with Google";
b.Click += new EventHandler(loginGoogle_Click);
loginPH.Controls.Add(b);
}
}
void Page_PreRender()
{
string s;
if (Session["loginId"] != null)
s = "Good";
else
s = "NULL";
loginPH.Controls.Add(new Label { Text = s });
}
以下是重构的代码,用于在PreRender
事件中执行控件添加(我删除了之前存在的测试占位符)。它应该工作相同,但不是。它总是添加登录按钮:
protected void Page_Load(object sender, EventArgs e)
{
using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
{
var response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
Session["loginId"] = response.ClaimedIdentifier;
break;
}
}
}
}
void Page_PreRender()
{
if (Session["loginId"] != null)
{
Label l = new Label();
l.Text = "Welcome " + Session["loginId"];
loginPH.Controls.Add(l);
Button b = new Button();
b.Text = "Logout";
b.Click += new EventHandler(logout_Click);
loginPH.Controls.Add(b);
}
else
{
Button b = new Button();
b.Text = "Log in with Google";
b.Click += new EventHandler(loginGoogle_Click);
loginPH.Controls.Add(b);
}
}
有什么想法吗?
答案 0 :(得分:2)
我认为您的问题更多地与您尝试在PreRender中连接事件处理程序有关。 在回发后,只有在处理了click事件之后才会创建按钮,这意味着将忽略该事件。
尝试使用页面范围声明按钮并在Page_Init中初始化它们:
protected Button a;
protected Button b;
void Page_Init(object sender, EventArgs e)
{
a = new Button();
a.Text = "Logout";
a.Click += new EventHandler(logout_Click);
b = new Button();
b.Text = "Log in with Google";
b.Click += new EventHandler(loginGoogle_Click);
}
然后在PreRender中,您可以决定使用哪个按钮:
void Page_PreRender(object sender, EventArgs e)
{
if (Session["loginId"] != null)
{
Label l = new Label();
l.Text = "Welcome " + Session["loginId"];
loginPH.Controls.Add(l);
loginPH.Controls.Add(a);
}
else
{
loginPH.Controls.Add(b);
}
}