简体   繁体   中英

MVC custom view routing based on controller structure

I need my ASP.NET MVC5 view structure to reflect the structure of my controllers.


The controllers of my application have the following structure:

Controllers
|--- Main
|    |--- HomeController.cs
|--- User
|    |--- HomeController.cs
|    |--- SettingsController.cs
|--- Admin
|    |--- HomeController.cs
|    |--- ManageController.cs

The controller structure is based on the user type, and the Main controllers are accessible to all users. My URLs are like this:

  • /Main/Home (default)
  • /User/Settings
  • /Admin/Manage/Users

But as you can see all namespaces have a HomeController , but when I want to create, for example, an Index view for User/HomeController it will be placed inside Views/Home/Index.cshtml . But I actually need this view to be here: Views/User/Home/Index.cshtml . Below an example structure of how I need the views to be structured.

Views
|--- Main
|    |--- Home
|    |    |--- Index.cshtml
|    |    |--- Contact.cshtml
|--- User
|    |--- Home
|    |    |--- Index.cshtml
|    |--- Settings
|    |    |--- Index.cshtml
|--- Admin
|    |--- Home
|    |    |--- Index.cshtml
|    |--- Manage
|    |    |--- Index.cshtml
|    |    |--- Users.cshtml

I tried using a custom RazorViewEngine but all examples I could find ( like this one ) wouldn't work for my situation. Is there a way to achieve this specific structure with custom routing?

I belive you're looking for areas.

Areas was avalable in MVC 4. And there is no difference in MVC 5.

Here you can find a details .

As others have pointed out, you could use Areas to structure your website (provided you only want 1 level).

If you want multiple levels of controllers ( /section1/sectiona/SomeController.cs ), then have a look at MvcCodeRouting .

如果区域不适合您,您可以指定所需的路径而不是使用默认值:

return View("user/home/index", model);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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