asp.net mvc的复杂的路由结构树路径 [英] asp.net mvc complex routing for tree path
问题描述
我想知道我怎么可以定义一个路由映射是这样的:
{的TreePath} / {行动} {ID}
TreeMap的动态,从这样的数据库加载:
图库/ GalleryA / SubGalleryA /浏览/ 3'
您可以创建一个自定义路由处理程序做到这一点。实际的路线是一个包罗万象的:
routes.MapRoute(
树,
树/ {*}路径,
新{控制器=树,行动=索引})
.RouteHandler =新TreeRouteHandler();
树处理看着路径,提取后一部分作为动作,然后重定向到控制器。动作部分也从路径中删除。添加{ID}部分应该是简单的。
公共类TreeRouteHandler:IRouteHandler
{
公众的IHttpHandler GetHttpHandler(RequestContext的的RequestContext)
{
字符串路径= requestContext.RouteData.Values [路径]作为字符串;如果(路径!= NULL)
{
INT IDX = path.LastIndexOf('/');
如果(IDX> = 0)
{
串actionName = path.Substring(IDX + 1);
如果(actionName.Length大于0)
{
requestContext.RouteData.Values [行动] = actionName;
requestContext.RouteData.Values [路径] =
path.Substring(0,IDX);
}
}
}返回新MvcHandler(RequestContext的);
}
}
您控制器然后就像你所期望的:
公共类TreeController:控制器
{
公众的ActionResult DoStuff(字符串路径)
{
计算机[路径] =路径;
返回查看(「指数」);
}
}
现在你可以调用URL像 /树/节点1 /节点2 /节点3 / DoStuff
。这一行动得到的路径是节点1 /节点2 /节点3
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'
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
这篇关于asp.net mvc的复杂的路由结构树路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!