Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting absolute URL to page in code

I am new to ASP.NET and am trying to convert a web application from using hard-coded deployment locations (ie, /base/path/index.aspx) to discovering them at runtime. If I use Response.Redirect(), I can express the path as '~/index.aspx' and, at runtime, ASP.NET will build the correct URL to send the redirect to based on where the web application is deployed.

There are places in the code where Javascript and/or HTML is generated dynamically and sent to the client as part of the response to force a new window. In these cases, I don't know how to get the actual URL that should be opened in the new window. Using ~ doesn't work in this case since the URL is being evaluated by the browser and not the server. Is there a class or method in ASP.NET that will give me the URL I am looking for? I'd look myself, but I don't even know how to properly phrase my question.

like image 646
Chris Lieb Avatar asked Jul 08 '09 16:07

Chris Lieb


2 Answers

The VirtualPathUtility class is what you are looking for.

Specifically you can use these methods:

VirtualPathUtility.ToAbsolute("~/");
VirtualPathUtility.ToAppRelative("~/");
like image 192
NerdFury Avatar answered Oct 11 '22 00:10

NerdFury


You could do something like this:

<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    var url = '<%= ResolveUrl("~/path/some_page.aspx") %>';
    window.open(url, 'name');
    </script>
</head>
<body>
    <form id="form1" runat="server"></form>
</body>
</html>
like image 44
Darin Dimitrov Avatar answered Oct 11 '22 02:10

Darin Dimitrov