I have seen this question a couple of times here in SO but none of them with any acceptable answer:
ASP.NET MVC @Url.Action includes current route data
ASP.NET M
Simple example:
public class ProductController : Controller
{
public ActionResult Edit(int id)
{
return View();
}
[Route("Product/Detail/{id:int}")]
public ActionResult Detail(int id)
{
return View();
}
}
Edit view contains only this:
@{ Layout = null;}
@Url.Action("Detail", "Cmr")
So when you run your site e.g. localhost:randomPort/Product/Edit/123
you get next response: /Product/Detail/123
Why? Because Route
attribute has required parameter id
. Id parameter is read from url, although we wrote only Url.Action(methodName, controller)
- without specifying parameter. Also it doesn't make sense to have a method detail without id.
In order for attributes to work next line must be added to RouteConfig.cs
:
public static void RegisterRoutes(RouteCollection routes)
{
...
routes.MapMvcAttributeRoutes();
...
}