I'm trying to pass a list of URL's with Id attributes from a controller to a view.
I can pass a <a href=...> link back but I don't think writing a 'localhost' absolute path is a clean way of approaching this. I cant pass an ActionLink back as it returns the full string. Is ther a simple solution to this problem? Thanks in advance.
2 Answers
Using this overload of the UrlHelper.Action() method and Request object you can get a complete URL including the route parameters such as IDs and the actual hostname of the application.
string url = Url.Action("action", "controller",
new System.Web.Routing.RouteValueDictionary(new { id = id }),
"http", Request.Url.Host);
UrlHelper is available in the controller via its Url property.
You can then pass such URL into your view.
It is also possible to use UrlHelper directly inside your view to create URLs for controller actions. Depends if you really need to create them inside the controller.
Edit in response to comments:
Wherever you need to place the URLs, this "URL builder" you are looking for is still the UrlHelper. You just need to pass it (or the generated URLs) where you need it, being it inside the controller, view or custom helper.
To get the links inside the unsorted list HTML structure you mention, you need to put anchors inside the list items like this:
<ul>
<li><a href="URL">Link</a></li>
...
</ul>
Then again you just need to get the URLs from somewhere and that would be from UrlHelper.
2 Comments
Simple and easy.
<a href="@Url.Action("action","controller",new {id = my_var_id})">text</a>
the route id = the parameter that is going to be inserted into your method.
eg.
function Details(int id) {
//id has the value of my_var_id
}
ActionLinkshould be dynamically rendering the path based on the location of the application, making it portable. (Rather than hard-coding the full path.) How is this not working?