How to generate a path/url from a Route in the Rou

2019-03-05 02:10发布

问题:

I have an ASP.NET MVC web application, and I've registered a number of routes in my Global.asax.

I would like to know how I can programmatically build (generate a string url) any one of those registered routes from within my Controller.

I did the same thing in Web Forms with .NET 4.0 using Page.GetRouteUrl(routeName, routeParams) but can't figure out how to do the same thing in MVC (I'm an MVC newbie).

回答1:

You could use the UrlHelper class inside your controller action.

public ActionResult Index()
{
    string address = Url.RouteUrl(new { 
        action = "foo", controller = "bar", id = "123" 
    });
    // TODO: do something with the url

    return View();
}