How to manually nest related files in Visual Studio

Henry Aung / 2 years ago

Normally in a project like ASP.NET MVC, you would have only cshtml files under "Views" folder, and JavaScript files will be typically places in a "Scripts" folder and SCSS files under a Scss folder and so on.

This is considered organization "by file-type".

However, another approach would be to organize the files and folders "by function" (i.e. related files are group together by their function, rather than their type).

Consider the following folder structure:

You have a typical Razor cshtml file, a JavaScript file and a SCSS file.

You can see from the file structure that all the files are related to part of the application that handles "Order/View"

Now it's all fine and dandy but now your Views folder is getting polluted with different types of files for each view.

To reduce this noise, Visual Studio has a little-known feature that allows related files to be nested by editing  the csproj file directly.

csproj files are XML files that can be manually opened and edit in any text-editor.

Obviously it is a Visual Studio generated XML file and shouldn't monkey around with unnecessarily. However, as you become a "Super User", there will be times when you would need to edit the csproj files manually.

DependentUpon Element

The DependentUpon element allows the related files to be nested under the Solution Explorer.

To make use of this, open the csproj file in Notepad and look for the file that you want to nest it part of the "main" file.

TIP

Make a backup copy of your csproj file before editing just in case you need to revert it back (unless your project is already versioned)

In our example, we look for the following XML:

<Content Include="Views\Order\View.scss" />

And then modify the XML element to become:

<Content Include="Views\Order\View.scss">
<DependentUpon>View.cshtml</DependentUpon>
</Content>

We then repeat the same process for View.js:

<Content Include="Views\Order\View.js">
<DependentUpon>View.cshtml</DependentUpon>
</Content>

After saving the csproj in Notepad, you can reload the project in Visual Studio.

Now you can see that all the related files are neatly nested under the main "View.cshtml":

A shortcoming with this approach is that Visual Studio currently does not show correct icon for nested files and you will only see the "blank" icon displayed in the Solution Explorer.

However, it will greatly reduce the noise in your project structure and make more sense of how the files are related when you are following the "organization by-function" principle.

;