我正在创建一个与游戏应用程序配合使用的网站,其中联盟可以互相对抗。 这是我在网页上的第一次尝试,我正在尝试将ID传递到另一个页面。问题是我的page_load第一次触发,我设置了ViewState变量,但随后我的主页加载导致所有内容都被重置。
第一页: FindOpponent.aspx(按钮单击设置ID,然后进入此处)
Context.Items["WarID"] = tw.ID;
Server.Transfer("ConfirmWarTimer.aspx");
第二页: ConfirmWarTimer.aspx(第一次调用Page_Load时一切正常.ViewState包含我的变量并启用了计时器)
protected void Page_load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ActivateTimer();
return;
}
}
public void ActivateTimer()
{
if (!tim.Enabled)
{
DBClassesDataContext db = new DBClassesDataContext();
if (Context.Items["WarID"] != null)
{
ViewState["WarID"] = Context.Items["WarID"];
var thisWar = from a in db.tblWars where a.ID == int.Parse(ViewState["WarID"].ToString()) select a;
foreach (var a in thisWar)
{
TimeSpan t = TimeSpan.Parse(a.CountDown.ToString());
ViewState["Hours"] = t.Hours;
ViewState["Minutes"] = t.Minutes;
ViewState["Seconds"] = t.Seconds;
ViewState["TimeStamp"] = a.TimeStamp.ToString();
}
}
lblStart.Value = ViewState["TimeStamp"].ToString();
tim.Enabled = true;
return;
}
}
然后调用主页init / preload / load。之后,在我的第二页上再次调用Page_Load,但这次Context.Items为空,ViewState为空,timer.enabled为false。
母版页面cs(这只是用我的项目创建的页面。我添加了page_load,因此菜单不会显示在default.aspx页面上。)
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
}
else
{
// Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if ((Request.Url.ToString().ToLower().IndexOf("default") > -1))
{
pnMenu.Visible = false;
}
else
{
pnMenu.Visible = true;
}
}
protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
{
Context.GetOwinContext().Authentication.SignOut();
}
我试图了解viewstate以及何时设置它以及在多次尝试和更改之后的地方,viewstate似乎永远不会在我的页面中停留。
如何在我的母版页“加载”执行完毕后让viewstate在第二页(ConfirmWarTimer.aspx)上保留?