Domanda

I'm trying to save a value on Page_Unload event, store it in Session (or ViewState) and then use it from javascript. However the Session's value only gets updated after postback/refreshing the page, but I need to avoid a page refresh, how can I achieve this?

Example:

the .cs

public void Page_Unload(object sender, System.EventArgs e)
{
    string s="some text";
    if (s.Contains("foo")) Session["bar"] = 37; else Session["bar"] = 38;
}

the .aspx

<script type="text/javascript">
   function tst() {
     alert('<%=Session["bar"]%>');
   }
</script>
È stato utile?

Soluzione 2

Page_Unload event is triggered after page is sent to client browser (Please refer to this link). Therefore, you cannot store any value to Session.

In your case, you might need to do a callback to avoid full page refresh (Please refer to this link). Then in the event triggered by the callback. After doing all the work needed to be done, you can do your check then store necessary variable to the Session for use in client javascript.

Altri suggerimenti

Page_Unload event is too late to assign a new value to Session State.

Instead, you want to use Page_PreRender event.

protected void Page_PreRender(object sender, EventArgs e)
{
   string s="some text";
   if (s.Contains("foo")) Session["bar"] = 37; else Session["bar"] = 38;
}

enter image description here

First, here is a useful page for understanding event lifecycle. http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx#general_page_lifecycle_stages.

When your page renders, the <%=Session["bar"]%> is replaced by the current value. Since your page has not yet "unloaded" this value has not been updated. In other words, this value is NOT read when the javascript code runs, but rather when the Page is rendered. To accomplish what you are attempting, you would need to set your value in the Pre_Render, rather than the Unload Event.

If Pre_Render doesn't work for you, I can imagine a solution where you would use a combination of an Asyncronous Method call and AJAX to get the value into your code. Here's a reference to how this works: http://msdn.microsoft.com/en-us/library/bb398998.aspx. Specifically look at the last section which is doing exactly what you are describing (i.e. getting a session value from client script).

  1. Add a script manager to the page.
  2. Set the PageMethods property to true
  3. Add a flag to session for "still working on it" and "done"
  4. Call your long running process to get the value using an asyncronous delegate in Pre_Render.
  5. In the Async callback set your session value and set the new flag to 'completed'
  6. In page unload call the Async delegate "EndXXX" method.
  7. Create a public static method that checks the value of the flag and if set to 'completed' returns the Session value you want.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top