Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

asp.net mvc - Get the VirtualPath From the Area, Controller and Action

I was wondering how to get a URL given the area, controller and action names. So far all I have managed to come up with is:

var httpContext = new HttpContextWrapper(HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(httpContext);

if (routeData != null) {
    var virtualPath = routeData.Route.GetVirtualPath(new RequestContext(httpContext, routeData), new RouteValueDictionary(new { area = "Pages", controller = "Home", action = "Index" }));

    if (virtualPath != null) 
        newNode.Url = "~/" + virtualPath.VirtualPath;
}

However it does not work. I was wondering if someone could help.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Incase anyone is wondering, here's the solution I have come up with:

// Set the context
var context = new RequestContext(new HttpContextWrapper(HttpContext.Current),
    new RouteData());
var urlHelper = new UrlHelper(context);

// Set the url
var url = urlHelper.Action("Index", "Home",
    new RouteValueDictionary(new { area = "Pages" }));

I hope this helps someone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...