我的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);
}
}
有任何想法吗?