ASP.NET MVC 5 dynamic controller routes

青春壹個敷衍的年華 提交于 2019-12-11 13:38:48

问题


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".


回答1:


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:

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


来源:https://stackoverflow.com/questions/35860959/asp-net-mvc-5-dynamic-controller-routes

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