Search code examples
c#asp.net-coreasp.net-core-mvc

How to navigate to a controller action in javascript?


I have a button in a page and onlick I'm calling:

var viewUser = function (e) {
    window.location = '@Url.Action("Index", "UsersManage")' + '/' + e.row.data.Id;
}

I have the following controller:

[Area("Admin")]
[Route("Users/Manage")]
public class UsersManageController : Controller
{
    [HttpGet("{key}")]
    public async Task<IActionResult> Index(string key)
    {
        return View();
    }
}

I would like that the url would be /Admin/Users/Manage/useridhere.

But when I click on the button I get an error 400 and the url is /Admin/UsersManage/useridhere.

What am I missing?

EDIT

I changed the Javascript function:

var viewUser = function (e) {
    window.location.href = '/Admin/Users/Manage/' + e.row.data.Id;
}

But I still can't reach the action. How exactly do I need to name my controller, action and view?


Solution

  • I think you should try url /Users/Manage/useridhere

    enter image description here

    We have [Route("Users/Manage")] so we shouldn't use the controller name. And the [Area("Admin")] doesn't affect the route if we use the default route in Program.cs, the Area attribute only asks the view to reach /Areas/Admin/Views/Chart/Index.cshtml path.

    enter image description here