views:

270

answers:

2

~/Folder1/UserControl1.ascx:

<%@ Control Language="C#" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>
<asp:HyperLink runat="server" NavigateUrl="?foo=bar">HyperLink1</asp:HyperLink>

~/UserControl2.ascx:

<%@ Control Language="C#"CodeBehind="WebUserControl2.ascx.cs" Inherits="WebApplication1.WebUserControl2" %>
<asp:HyperLink runat="server" NavigateUrl="?foo=bar">HyperLink2</asp:HyperLink>

Result:

http://localhost/Folder1/?foo=bar

http://localhost/?foo=bar

Why does it happen?

+1  A: 

WHen you do not have a / or ~ at the beginning of the path, it is considered relative to the CURRENT position.

From a user control, current position is the position of the control.

Mitchel Sellers
+1  A: 

The links are resolve relative to the directory of the user control, they actually call ResolveClientUrl(); internally, so you see this same behavior.

Description from MSDN:

The URL returned by this method is relative to the folder containing the source file in which the control is instantiated. Controls that inherit this property, such as UserControl and MasterPage, will return a fully qualified URL relative to the control.

Resolving the urls with Page.ResolveClientUrl() in the code-behind will solve the problem.

Nick Craver
Can I call this method from гыук сщтекщд code located in sub-folder? I.e. this.Page.ResolveClientUrl() where this : UserControl
abatishchev
@abatishchev - Yes, this should work just fine
Nick Craver
@Nick Craver: Then it's strange why does it not work for me.. urlSearch.NavigateUrl = this.Page.ResolveClientUrl("?search=true") makes url's address still the same - http://localhost/Approve/?search=true. Maybe I do something wrong?
abatishchev
@abatishchev - If this link's always relative to the page, don't use the controls at all, just `<a href="?search=true">Link Text</a>`
Nick Craver