Search code examples
c#asp.net-mvcasp.net-mvc-routing

MVC attribute routing issues


I decorate an action (in my Home controller) like so:

[Route("view-book")]
public ActionResult ViewBook(int? id1, string id2)

In my View, I populate some hyperlinks using javascript:

tbody = tbody + '<a href="@Url.Action("ViewBook", "Home")/' + item.Id + '/' + item.Slug + '">View Book</a>';

With the above code, the URL of the hyperlink renders correctly. E.g:

https://localhost:44306/view-book/1/this-book

However, the ActionResult doesn't get hit. So, I change the routing decoration to be:

[Route("view-book/{id1:int?}/{id2}")]
public ActionResult ViewBook(int? id1, string id2)

And now the URL renders incorrectly like so:

https://localhost:44306/Home/ViewBook/1/this-prop

However, if I manually change the URL to the correct URL like above:

https://localhost:44306/view-book/1/this-prop

The ActionResult then gets hit!

How do I resolve this?


Solution

  • You can use multiple routes on the action.

    [HttpGet]
    [Route("view-book")] // Matches GET view-book
    [Route("view-book/{id1:int?}/{id2}")] //Matches GET view-book/1/slug
    public ActionResult ViewBook(int? id1, string id2) { ... }
    

    That way, when you build the route in javascript, the first route should now allow you to render the correct URL before because @Url.Action("ViewBook", "Home") should resolve to view-book as desired, and the second route will allow the action to be invoked.