MVC Attribute routing with Url.Action not resolving route

Simon picture Simon · Mar 28, 2016 · Viewed 8.2k times · Source

I cannot get @Url.Action to resolve to the url I am expecting based on the attribute route I have applied:

My action (SearchController but with [RoutePrefix("add")])

     [Route("{searchTerm}/page/{page?}", Name = "NamedSearch")]
     [Route("~/add")]
     public ActionResult Index(string searchTerm = "", int page = 1)
     {
       ...
     }

Call to Url.Action

@Url.Action("Index", new { controller = "Search", searchTerm = "replaceMe", page = 1 })

This results in a url of

/add?searchTerm=replaceMe&page=1

I would expect

/add/replaceMe/page/1

If I type the url manually then it resolves to the correct action with the correct parameters. Why doesn't @Url.Action resolve the correct url?

Answer

Shyju picture Shyju · Mar 28, 2016

Since you have a name for your pretty route definition, you may use the RouteUrl method.

@Url.RouteUrl("NamedSearch", new {  searchTerm = "replaceMe", page = 1})

And since you need add in the url, you should update your route definition to include that in the url pattern.

[Route("~/add")]
[Route("~/add/{searchTerm?}/page/{page?}", Name = "NamedSearch")]
public ActionResult Index(string searchTerm = "", int page = 1)
{
 // to do : return something
}