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
459 views
in Technique[技术] by (71.8m points)

asp.net mvc complex routing for tree path

I am wondering how can I define a routing map like this:

{TreePath}/{Action}{Id} 

TreeMap is dynamically loaded from a database like this:

 'Gallery/GalleryA/SubGalleryA/View/3'
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can create a custom route handler to do this. The actual route is a catch-all:

routes.MapRoute(
    "Tree",
    "Tree/{*path}",
    new { controller = "Tree", action = "Index" })
        .RouteHandler = new TreeRouteHandler();

The tree handler looks at path, extracts the last part as action, and then redirects to the controller. The action part is also removed from path. Adding the {id} part should be straightforward.

public class TreeRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        string path = requestContext.RouteData.Values["path"] as string;

        if (path != null)
        {
            int idx = path.LastIndexOf('/');
            if (idx >= 0)
            {
                string actionName = path.Substring(idx+1);
                if (actionName.Length > 0)
                {
                    requestContext.RouteData.Values["action"] = actionName;
                    requestContext.RouteData.Values["path"] = 
                        path.Substring(0, idx);
                }
            }
        }

        return new MvcHandler(requestContext);
    }
}

Your controller then works as you would expect it:

public class TreeController : Controller
{
    public ActionResult DoStuff(string path)
    {
        ViewData["path"] = path;
        return View("Index");
    }
}

Now you can call URL like /Tree/Node1/Node2/Node3/DoStuff. The path that the action gets is Node1/Node2/Node3


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

...