Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 817
Kailas Mane Avatar asked Oct 25 '12 05:10

Kailas Mane


3 Answers

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

like image 129
Kailas Mane Avatar answered Nov 14 '22 03:11

Kailas Mane


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.

like image 34
Erik Funkenbusch Avatar answered Nov 14 '22 04:11

Erik Funkenbusch


For future visitors: use areas.

Walkthrough: Organizing an ASP.NET MVC Application using Areas

like image 3
Jeroen Avatar answered Nov 14 '22 03:11

Jeroen