ASP.NET MVC Url.Action adds current route values to generated url

前端 未结 7 1210
孤独总比滥情好
孤独总比滥情好 2020-12-07 20:26

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

7条回答
  •  攒了一身酷
    2020-12-07 20:55

    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();
      ...
    }
    

提交回复
热议问题