Kailas Mane
Kailas Mane

Reputation: 1935

Add views in sub-folders in ASP.NET MVC 3

I am working on ASP.NET MVC 3 project. I want to divide controllers, models, and views in sub-folders for the sake of simplicity. I able to do it with controllers and models but when i create a view it creates automatically to root folder Views, Is there any way to solve this problem?

eg. I can create

model class as,

Models/Finance/Bank.cs
Models/Finance/Finance.cs
Models/Production/Production.cs

controller as,

Controllers/Finance/BankController/Create
Controllers/Finance/BudgetController/Create
Controllers/Production/ProcessController/Create

but where i tried to create view for above actions, it creates in to,

Views/Bank/Create.aspx
Views/Budget/Create.aspx
Views/Process/Create.aspx

I want it should be like,

Views/Finance/Bank/Create.aspx
Views/Finance/Budget/Create.aspx
Views/Prodution/Process/Create.aspx

Is there any way to create views in same sub-folder as of that created for Controllers and models? thanks!

Upvotes: 21

Views: 34726

Answers (4)

Jeroen
Jeroen

Reputation: 175

For future visitors: use areas.

Walkthrough: Organizing an ASP.NET MVC Application using Areas

Upvotes: 2

Kailas Mane
Kailas Mane

Reputation: 1935

following steps worked for me,

  1. Create sub-folders as you want in Views (root folder). in my case it was Finance & Production.

  2. Simply drag automatically created folders in Views in to appropriate Sub-folders. in my case Bank & Budget in to Finance and Process in to Production

  3. While you return a view from controller action, give full path of view as,

    return View("~/Views/Finance/Bank/Create.aspx")

    return View("~/Views/Finance/Budget/Create.aspx")

    return View("~/Views/Production/Process/Create.aspx")

Upvotes: 34

ChunHao Tang
ChunHao Tang

Reputation: 594

View's named is According to name of Controller, you should follow the rule.
If you wanna it create Views/Admin/Create, then your CustomerController.cs should be named AdminController.cs.

Upvotes: -1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

Models and Controllers are compiled source files. They get compiled into a DLL, and as such, they can literally be put anywhere in the project and it won't make a difference. These classes are have no concept of their location in the filesystem because they don't exist in the filesystem once compiled.

Views, on the other hand are different. They are text files that are deployed to the server and loaded and parsed at run-time, thus the framework has to know where to find them.

The tooling will always create the views in the ~\Views\Controller folder (or ~Areas\AreaName\Controller folder). You can move them anywhere you want after that, but you will have to give the entire folder path to the View() method (including .cshtml). Or you will have to implement a custom ViewEngine that sets the search paths where you want them.

Upvotes: 19

Related Questions