0

Maybe a chicken/egg problem.

Based on this answer: https://stackoverflow.com/a/27190520/1438215

I want to use javascript to populate the value of an asp.net hidden field (as soon as it's possible), and then access the value of that populated field in the server-side Page_Load event.

Sample:

aspx portion:

<div id="div_BrowserWindowName" style="visibility:hidden;">
    <input type="hidden" name="ctl00$ctl00$BodyContent$MainContent$hf_BrowserWindowName" id="BodyContent_MainContent_hf_BrowserWindowName" />
</div>
<script type="text/javascript">
            function PopBrowserWindowName() {
    if (typeof window.name != undefined) {
        if (window.name == '') {
            var d = new Date();
            window.name = '_myWnd_' + d.getUTCHours() + d.getUTCMinutes() + d.getUTCSeconds() + d.getUTCMilliseconds();
        }
        var eDiv = document.getElementById('div_BrowserWindowName');
        var e = eDiv.getElementsByTagName('input')[0];
        e.value = window.name;
        alert(e.value);
    }
          }

    window.onload = PopBrowserWindowName();
</script>    

aspx.cs portion (page_load) event:

if (hf_BrowserWindowName != null)
       {string winID = hf_BrowserWindowName.Value;}

This does works during postbacks, but does not work on the page's initial load.

Community
  • 1
  • 1
Douglas Timms
  • 684
  • 6
  • 20

1 Answers1

1

Prior to Page_Load, there is no HTML or JavaScript because the Response has not been sent to the client yet. You need to learn the ASP.NET Page Lifecycle.

You can use server side code to populate the information, or after the page is sent to the client you can have some JavaScript populate the information.

mason
  • 31,774
  • 10
  • 77
  • 121
  • The answer, though not the answer I was hoping for. – Douglas Timms Jan 14 '15 at 21:26
  • @DouglasTimms Why are you trying to get the window name on the server side anyways? – mason Jan 14 '15 at 21:35
  • Desperate attempt to continue being able to use session variables, yet still have them be unique across multiple tabs within single browser. Trying to implement this solution offered by someone else: http://stackoverflow.com/a/27190520/1438215 – Douglas Timms Jan 14 '15 at 21:44
  • @DouglasTimms Session isn't supposed to be unique, and you're really fighting the architecture if you try to. Concede defeat on that. If you need to save state specific to a certain page, then use ViewState, and pass the data to subsequent pages via query string or posting to different pages. – mason Jan 14 '15 at 21:49