ASP.Net HyperLink's NavigateUrl changes after rendering in to HTML Anchor
-
25-09-2019 - |
Question
I am quite new to ASP.Net. I have a Master.aspx and a Page1.aspx and Page2.aspx, all in the same directory.
Master:
<asp:HyperLink NavigateUrl="Page1.aspx" runat="server" Text="Page 1" />
<asp:HyperLink NavigateUrl="Page2.aspx" runat="server" Text="Page 2" />
both the Page1 and Page2 gets rendered from above master page.
all three are in a vertual directory which is mapped as a subdomain here are the details:
Virtual Drectory: dirvir Domain: dirvir.example.com
now when I open any of the page say:
http://dirvir.example.com/Page1.aspx
the Hyperlinks are rendered containing
href="../virdir/Page1.aspx"
href="../virdir/Page2.aspx"
respectively.
On click of them it takes me to
http://dirvir.example.com/dirvir/Page1.aspx
http://dirvir.example.com/dirvir/Page2.aspx
where as I wanted it to be
http://dirvir.example.com/Page1.aspx
http://dirvir.example.com/Page2.aspx
I can achive the same by using <a> but i need them on the code behind too so thats not desired.
Note: using <a> with runat server also behaves in the same way HyperLink does.
Solution
Can you try this as indicated below change the NavigateUrl,
<asp:HyperLink NavigateUrl="~/Page1.aspx" runat="server" Text="Page 1" />
<asp:HyperLink NavigateUrl="~/Page2.aspx" runat="server" Text="Page 2" />
Or
<asp:HyperLink NavigateUrl="/Page1.aspx" runat="server" Text="Page 1" />
<asp:HyperLink NavigateUrl="/Page2.aspx" runat="server" Text="Page 2" />
OTHER TIPS
In Visual Studio click on the Project Name in the Solution Explorer. Once you do this, you will find a property under the properties window called Virtual Path
, which will have the value /dirvir
. Change this to /
If you don't need it to be a server-side link, just use a regular anchor tag and let ASP.NET figure out the correct path based on your virtual directory for your web application:
<a href="<%: ResolveURL("~/Page1.aspx")%>">Page 1</a>