简体   繁体   中英

Url.Action is not working with routes specified in controller using route annotation

I have an AdminController that looks like the following:

AdminController [Route("admin")]

Index() (landing page for all administrative content)

UserIndex() - [Route("users")]
UserDetails() - [Route("users/details/{id}")]

RoleIndex() - [Route("roles")]
RoleDetails() - [Route("roles/details/{id}")]

These equal the following URL patterns:

admin/users
admin/users/details/1

However, if I try to do the following in my view it does not work:

Url.Action("UserDetail", "Admin")

shouldn't this be smart enough to output: '/admin/users/details'?

It only works if I do Url.Action("Index", "Admin") since there is no route tag with it.

Update:

I am attempting to use Kendo Template Syntax with a Kendo Grid ClientTemplate column:

    columns.Bound(c => c.Id).ClientTemplate(
        "<a href='" +
            Url.Action("UserDetails", "Admin") +
            "/#= Id #'" +
        ">Details</a>"
    );

The link for each row ends up looking like the following: 'localhost:9000/123' The /admin/users/detail is completely being ignored...

And here is my exact declaration of the method I am trying to call in the AdminController:

// GET: Users/Details/5
[Route("users/details/{id}")]
public async Task<IActionResult> UserDetails(string id)
{
}

Recheck the routes and actions for controller

[Route("admin")]
public class AdminController : Controller {
    // GET admin
    [Route("")]
    public IActionResult Index() {...}

    //GET admin/users
    [Route("users")]
    public IActionResult UserIndex() {...}

    //GET admin/users/details/1
    [Route("users/details/{id}")]
    public IActionResult UserDetails(string id) {...}

    //GET admin/roles 
    [Route("roles")]
    public IActionResult RoleIndex() {...}

    //GET admin/roles/details/1
    [Route("roles/details/{id}")]
    public IActionResult RoleDetails(string id) {...} 

}

shouldn't this be smart enough to output: '/admin/users/details'?

according to your routes setup /admin/users/details does not exist.

Its waiting for a request to /admin/users/details/{id} where {id} is a userid . So when Url.Action("UserDetail", "Admin") is requested, there is nothing to match.

Url.Action("UserDetail", "Admin", new { id = "1" })

You can make the id parameter optional by updating the route

[Route("users/details/{id?}")]

This will allow users/details to work. but the value of id parameter will default to null .

It only works if I do Url.Action("Index", "Admin") since there is no route tag with it

It only works with Url.Action("Index", "Admin") because convention matches Index by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM