Why is my session variable declared in master page blank on a web page?

大憨熊 提交于 2019-12-12 21:26:24

问题


I declared in master page load:

Session["sessionString"] = "stringX";

in my web page on load also, i call it

string sessionString= (string)Session["sessionString"];

i debug and value in web page is "" what is wrong?


回答1:


JW Lim is correct...content page's load event will fire before Master page load.

@user3445314 , you can use "Session_Start" event in Global.asax and set values same as you set in master page.

"Session_Start" event fires first and then your content page load event occur.

I hope this may be solve your problem




回答2:


The Page_Load event of a content page is called before the Page_Load event of the master page (see this SO answer and MSDN article). Hence, when you call

string sessionString= (string)Session["sessionString"];

in your web page, Session["sessionString"] does not contain any value yet and defaults to an empty string.

As a workaround, you could set the value of Session["sessionString"] on the Init or PreLoad events of your master page.




回答3:


Declare Session in Master PreRender

protected override void OnPreRender(EventArgs e)
{
   Session["sessionString"] = "stringX";
}

And get it by ContetPage OnUnload event

protected override void OnUnload(EventArgs e)
{
   string sessionString= (string)Session["sessionString"];
}


来源:https://stackoverflow.com/questions/22624476/why-is-my-session-variable-declared-in-master-page-blank-on-a-web-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!