ASP.NET MVC page/subpage routing

﹥>﹥吖頭↗ 提交于 2019-12-23 10:59:09

问题


I'm try to figure out how to handle the following scenario. In general, i have a bunch of records in a table. All of these have ID and ParentID fields to form a tree.

Page1
 - Page2
 - Page3
Page4
 - Page5
 -- Page6

Now, i want my routes for Page3 and Page6 to be like /Page1/Page6 and /Page3/Page5/Page6 respectivelly. That is, i want to include all parents in the URL.

How to set my controller action/routing to achieve the above result?

Edit: Forgot to mention that the above structure will be dynamic - nodes can be added/deleted/change parent, etc.


回答1:


You could use a wildcard match.

A possible route:

routes.MapRoute("SomeName", "{*Page}", new { controller = "ControllerName", action = "ActionName" });

and in the action accept the string Page, and parse it manually, perhaps with a split?

This might also be useful: URL Routing




回答2:


Note that the controller name and action are fixed and not based on the url.

// place the more specific route first
routes.MapRoute("r1", "{parent}/{child}/{subchild}", 
    new { controller = "Page", action = "Index", parent = parent, child = child, subchild = subchild });

routes.MapRoute("r2", "{parent}/{child}", 
    new { controller = "Page", action = "Index", parent = parent, child = child });


public class PageController
{
    public ActionResult Index(string parent, string child, string? subchild)
    {
        // stuff
    }
}



回答3:


You should use

routes.MapRoute("Page6", "Page3/Page5/Page6", new { controller = "Page6", action = "Index" });

or maybe using Regular Expression Routing

http://blog.sb2.fr/post/2009/01/03/Regular-Expression-MapRoute-With-ASPNET-MVC.aspx



来源:https://stackoverflow.com/questions/411054/asp-net-mvc-page-subpage-routing

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