I have a page on my site, for purposes of this example lets say http://myhost/Pages/Default.aspx. On Default.aspx I have a user control called MyControl.ascx which lives in /Controls/MyControl.ascx. So the tree looks something like this
Whenever I place a HyperLink control on MyControl.ascx and specify a NavigateUrl, this path is relative to the control, not the URL of the page. So for instance if in NavigateUrl I specified "AboutMe.aspx", the URL would be rendered as http://myhost/Controls/AboutMe.aspx instead of http://myhost/Pages/AboutMe.aspx. Is there any way I can make this relative to the page URL? I've tried the solution here: Relative path from an ASP.NET user control NavigateUrl but it didn't work for me.
Edit
To clarify, I'd like this to be generic enough so that if I didn't know what the path was the solution would work. So I don't really want to harcode "~/Pages/Default.aspx" in the NavigateUrl
You have a bunch of options:
You could hardcode the Url using the ~
operator which give you the root and then define it from there like: ~/Pages/AboutMe.aspx
. Keep in mind that the ~
operator is recognized only for server controls and in server code.
You could also use the ..
to get you to where you want as it will navigate back up the folder structure like: ../Pages/AboutMe.aspx
You could create a helper methods to return you a valid root to your Pages folder, Images, Javascript, etc...
The HttpRequest.ApplicationPath
will get your the virtual application's root path on the server which you can use to build off.
For more information on Pathing options you should read this article on MSDN:
ASP.NET Web Project Paths
EDIT: Based on your edit to your question, you should then pass in the relative URL into you user control via a property. Let the page that uses the control define the relative path to the resource it will require.
The best way to achieve this is to use
string.Format("{0}", Page.Request.Url.PathAndQuery);
in NavigateUrl property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With