简体   繁体   中英

passing variable from asp.net page to new page using javascript

The following is on my asp.net page written in c#. Where someURL is asp.net string variable that contained a html link such as http:\\www.somewebsite.com.

ClientScript.RegisterStartupScript(typeof(Page), "openPage", "<script type='text/JavaScript'>var link1 = document.getElementById('<%=someURL.ClientID%>');window.open(link1);</script>");

The objective is when the above javascript executed it will open a new browser page with the url contained inside the someURL string (http:\\www.somewebsite.com, etc.)

My problem was that it opens a blank page with nothing in the url. And I think I know why... the someURL variable referenced inside the javascript code was not from the calling asp.net page.

Am I right? Any suggestion on how to achieve my objective?

Thank you.

Not sure of the purpose of this. But the variable link1 is a reference to a DOM element.

you need to get the text (depending on what type of control someURL is in your ASP page) value of that DOM element in order to pass it to the other script.

This is by no means elegant or recommended but will work

C# - in your codebehind page

public string nextURL = "http://yourdomain.com/yourpage.aspx"

ASP.NET - in your aspx page

<script type="text/javascript">

  var myLink = '<%= nextURL %>';

  function newPage() {
    window.open(myLink);
  }

</script>

For the benefit of those new learners, after a bit of struggle here is my final code that will do the job for me:

In my calling .cs file:

   protected String someURL;  //global variable

    ClientScript.RegisterStartupScript(typeof(Page), "openPage", "<script type='text/JavaScript'>window.open(currentLinkURL);</script>");

In my .aspx file:

var currentLinkURL = '<% = someURL %>';  //currentLinkURL is a javascript variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM