在Razor View中为包含参数的属性路径创建URL

时间:2017-02-15 17:51:31

标签: asp.net-mvc razor asp.net-mvc-5 attributerouting

我在下面的控制器中指定了一个路由,其中​​包含与操作上的重载相匹配的参数。

public class OrganisationsController : Controller
{
    [HttpGet]
    [Route("organisations/{id}/employees")]
    public ActionResult Employees(int id)
    {
        //  Some code here
    }
}

我尝试使用@Html.ActionLink在Razor视图中创建网址以匹配控制器上指定的路由,例如localhost:55416/Organisations/2/Employees,但我还是无法让它工作。

我能够得到的最接近的是localhost:55416/Organisations/Employees/2,但由于路线错误而无法正常工作,或者localhost:55416/Organisations/Employees?id=2实际上可以作为Organizations控制器上的员工操作被点击,但它只是一个查询字符串然后否定了首先添加[Route("organisations/{id}/employees")]路由的目的。

我在互联网上找到的所有示例和帖子都会处理最后的参数,例如[Route("organisations/employees/{id}")],而不是控制器和操作之间的参数。

我没有尝试将自定义路由添加到RouteConfig,因为在我看来,URL是根据控制器上指定的路径首先需要正确的起点,或者是我错了吗?

我有没有办法按照我希望它使用ActionLink的方式生成网址,或者我还有其他方法可以执行此操作吗?

1 个答案:

答案 0 :(得分:0)

应该归功于Sam,他提供的ActionLink是正确的,当我尝试它时它没有工作的原因是因为我没有将routes.MapMvcAttributesRoutes();行添加到项目的RouteConfig.cs中我在尝试创建网址后,添加了localhost:55416/Organisations/2/Employees操作链接生成的预期@Html.ActionLink("Employees", "Employees", "Organisations", new { id = item.Id }, null)网址。

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}