简体   繁体   English

ASP.NET MVC 5动态控制器路由

[英]ASP.NET MVC 5 dynamic controller routes

I'm having a challenge figuring out the best way to define my hierarchical based routes dynamically. 在寻找动态定义基于层次的路由的最佳方法方面,我遇到了挑战。

I'm looking to achieve database driven links similar to the below: 我正在寻找实现类似于以下内容的数据库驱动链接:

/Illinois/
/Illinois/Chicago/
/Illinois/Chicago/Id
/California/
/California/Los-Angeles/
/California/Los-Angeles/Id
/New-York/
/New-York/New-York-City/
/New-York/New-York-City/Id

And so on, I don't want to have to define a controller for each state, but I'm not 100% against if if it's "the right way". 依此类推,我不想为每个状态都定义一个控制器,但是如果这是“正确的方式”,我并不是100%反对的。

You can create a controller like HomeController and use route attributes on the top of this controller and related action to hide the route url and call your locations and ids in route like this: 您可以创建一个类似HomeController控制器,并在该控制器和相关操作的顶部使用路由属性来隐藏路由网址,并在路由中调用您的位置和ID,如下所示:

[RoutePrefix("")]
public class HomeController : Controller
{
    Route("{state?}/{city?}/{id?}")
    public ActionResult Index(string state, string city, int id)
    {
        //your codes
        return View();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM