ASP.Net C# ResolveClientUrl inside Class

五迷三道 提交于 2019-12-03 05:51:20

问题


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?


回答1:


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);



回答2:


Instead of calling ResolveClientUrl on the Page object (or any controls), you can also use VirtualPathUtility.ToAbsolute("~/home.aspx"); which will give you the same result as calling ResolveUrl("~/home.aspx");




回答3:


Bit old but might help someone. Using :

using System.Web.UI;

And in code:

new Control().ResolveClientUrl("Path");

Worked for me, I use Web Application and not Web Site solution, though.

Regards




回答4:


I found VirtualPathUtility.ToAbsolute to work very well for my purpose.

Worked perfectly:

protected void build_Menu() 
{

    StringBuilder sb = new StringBuilder();

    sb.Append("<li><a href='" + VirtualPathUtility.ToAbsolute("~/Default.aspx'>Home</a></li>"));
    sb.Append("<li><a href='" + VirtualPathUtility.ToAbsolute("~/CARS/Default.aspx'>Cars</a></li>"));
    sb.Append("<li><a href='" + VirtualPathUtility.ToAbsolute("~/AIRPLANES/Default.aspx'>Airplanes</a></li>"));
    sb.Append("<li><a href='" + VirtualPathUtility.ToAbsolute("~/MOTORCYCLES/Default.aspx'>Motorcycles</a></li>"));
    sb.Append("<li><a href='" + VirtualPathUtility.ToAbsolute("~/REPORTS/Default.aspx'>Reports</a></li>"));
    sb.Append("<li><a href='" + VirtualPathUtility.ToAbsolute("~/MANUALS/Default.aspx'>Manuals</a> </li>"));
    sb.Append("<li><a href='" + VirtualPathUtility.ToAbsolute("~/ADMINISTRATION/Default.aspx'>Administration</a></li>"));


    MENUfromCodeBehind.Text = sb.ToString();

}


来源:https://stackoverflow.com/questions/2238519/asp-net-c-sharp-resolveclienturl-inside-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!