ASP.NET MVC: URL Route

What is the easiest way to get the URL (relative or absolute) for a route in MVC? I saw this code here on SO, but it seems a bit detailed and does not list RouteTable.

Example:

List<string> urlList = new List<string>(); urlList.Add(GetUrl(new { controller = "Help", action = "Edit" })); urlList.Add(GetUrl(new { controller = "Help", action = "Create" })); urlList.Add(GetUrl(new { controller = "About", action = "Company" })); urlList.Add(GetUrl(new { controller = "About", action = "Management" })); 

FROM

 protected string GetUrl(object routeValues) { RouteValueDictionary values = new RouteValueDictionary(routeValues); RequestContext context = new RequestContext(HttpContext, RouteData); string url = RouteTable.Routes.GetVirtualPath(context, values).VirtualPath; return new Uri(Request.Url, url).AbsoluteUri; } 

What is the best way to learn RouteTable and get the URL for this controller and action?

+4
source share
2 answers

How about this (in the controller):

  public IEnumerable<SiteMapEntry> SiteMapEntries { get { var entries = new List<SiteMapEntry>(); foreach (var route in this.Routes) { entries.Add(new SiteMapEntry ( this.Url.RouteUrl(route.Defaults), SiteMapEntry.ChangeFrequency.Weekly, DateTime.Now, 1F)); } return entries; } } 

If the controller has an element:

 public IEnumerable<Route> Routes 

Note:

 this.Url.RouteUrl(route.Defaults) 
0
source

Use the UrlHelper class: http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.aspx

You can use it with an Url object in your controller. To map an action, use the Action method: Url.Action("actionName","controllerName"); . A complete list of overloads for the Action method is here: http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action.aspx

so your code will look like this:

  List<string> urlList = new List<string>(); urlList.Add(Url.Action("Edit", "Help")); urlList.Add(Url.Action("Create", "Help")); urlList.Add(Url.Action("Company", "About")); urlList.Add(Url.Action("Management", "About")); 

EDIT: It seems from your new answer that you are trying to create a site map.

Take a look at this Codeplex project: http://mvcsitemap.codeplex.com/ . I did not use it myself, but it looks pretty solid.

+7
source

Source: https://habr.com/ru/post/1309383/


All Articles