Reputation: 1951
I'm getting unexpected behavior in a Core 2.0 MVC app. Check this out:
I have a controller "ProfileController.cs" with simple methods:
public async Task<IActionResult> Index()
{
return View();
}
public async Task<IActionResult> Edit()
{
return View();
}
I've got the following markup in Profile/Index.cshtml:
<a asp-controller="Profile" asp-action="Edit">Edit Profile</a>
I'm using the following route mapping in Startup.cs:
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
But here is CRAZY behavior I am seeing:
The anchor tag ALWAYS generates and results in profile/index!
No matter what. asp-action="Edit"
is completely ignored and results in "index" or even "index/2" if additional params are on the url.
Why?
I know my routing is working because simply entering /profile
or /profile/index
or /profile/edit
renders the proper pages.
Upvotes: 2
Views: 675
Reputation: 1951
OK, this is half an answer. I resolved the issue, but the question of what magic the Razor engine is applying is still a mystery.
I overlooked this mistaken route applied to a POST method in the same ProfileController mentioned above:
[HttpPost]
[Route("[controller]/Index")]
public async Task<IActionResult> Edit([FromForm]User m)
{
// do stuff
return View();
}
Note the "/Index" action applied to the method called "Edit" (oops!)
Removing/fixing that route fixed the main problem:
[HttpPost]
[Route("[controller]/Edit")]
public async Task<IActionResult> Edit([FromForm]User m)
{
// do stuff
return View();
}
BUT it still raises the question: why on earth did the Razor engine apply the wrong thing by (apparently, magically) sniffing around and looking at a POST route that has nothing to do with the action requested? (and remember, typing /profile/edit
into the URL worked fine, routing was working for GET despite my blunder).
Furthermore, it did not fix the issue where parameters of the current url were being applied to the path...
If I was on /profile/index
the rendered action would be correct as /profile/index
. But if I was on /profile/Index/2
the rendered action would be wrong as /profile/Index/2
. I was NOT expecting the id to be included in the action . To correct this, I had to add asp-route-id=""
as follows:
<a asp-controller="Profile" asp-action="Index" asp-route-id="">View Profile</a>
This behavior might be by-design, but I think that magical routing issue above has to be a bug.
Upvotes: 1