How to generate URL for the action with attribute routing in Asp.Net MVC

北战南征 提交于 2020-07-08 20:37:07

问题


public class HomeController : Controller
{
    [Route("Users/about")]
    [Route("Users/WhoareWe")]
    [Route("Users/OurTeam")]
    [Route("Users/aboutCompany")]
    public ActionResult GotoAbout()
    {
        return View();
    }
}

I have many routes defined for action GotoAbout().

How to create route URL in razor page programmatically when generate URL for action like home/users/about ?


回答1:


Reference Attribute Routing in ASP.NET MVC 5 - Route Names

You can specify a name for a route, in order to easily allow URI generation for it.

For example, for the following route:

[RoutePrefix("Home")]
public class HomeController : Controller {
    [Route("Users/about", Name = "Users_About")]
    [Route("Users/WhoareWe")]
    [Route("Users/OurTeam")]
    [Route("Users/aboutCompany")]
    public ActionResult GotoAbout() {
        return View();
    }
}

you could generate a link using Url.RouteUrl:

<a href="@Url.RouteUrl("Users_About")">About</a>

which would resolve to

<a href="home/users/about">About</a>


来源:https://stackoverflow.com/questions/44619883/how-to-generate-url-for-the-action-with-attribute-routing-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!