Search code examples
c#asp.netclassrelative-pathresolveclienturl

ASP.Net C# ResolveClientUrl inside Class


I have the following code:

public class NavigationPath
{
    private string menuItems = "<li>" +
                                    "<a href=\"#\">home</a>" +
                               "</li>";

But I would like to have:

public class NavigationPath
{
    private string menuItems = "<li>" +
                                    "<a href=\"" + ResolveClientUrl("~/home.aspx") + "\">re</a>" +
                               "</li>";

However, I am not able to use ResolveClientUrl inside a Class. Any ideas?


Solution

  • ResolveClientUrl is a member of the System.Web.UI.Control class, hence it's accessible directly as:

    var url = ResolveClientUrl("~/Some/Url/");
    

    when called within the code of your asp.net page.

    To use it inside a class you're going to have to pass the Page (or a control on the page) into the class in its constructor. Even then I'm not sure you'd be able to use it in the way you've indicated. You'd probably have to do something similar to:

    public class NavigationPath
    {
      private string menuItems = string.Empty;
    
      public NavigationPath(Page page)
      {
        menuItems = "<li>" + "<a href=\"" + page.ResolveClientUrl("~/Home.aspx") + "\">home</a>" + "</li>";
      }
    }
    

    And then inside your asp.net page do something like:

    var navPath = new NavigationPage(this);