How can I avoid naming my View Component cshtmls "Default.cshtml" in ASP.NET Core MVC?

2k Views Asked by At

It seems that in ASP.NET Core MVC, if I want to use a View Component, I have to put them in Views\Shared\Components\[ViewComponentName], and then name the file "Default.cshtml".

This is rather frustrating, as in the beginning of a large project I am helping to port from Perl CGI, I'm creating a good number of View Components and having five tabs in Visual Studio all named Default.cshtml is confusing.

Is there any way I can avoid this naming convention? Maybe even take them out of their folders so that the file will look like…?

Views\Shared\Components\[ViewComponentName].cshtml

I don't know if there are just some settings I can tweak or what. For the most part, I'm very new to ASP.NET, and still figuring things out. Using ASP.NET Framework instead of ASP.NET Core is an option, though I'd prefer not to, as a lot of the boilerplate is already done.

The documentation on ViewComponents says this:

We recommend you name the view file Default.cshtml and use the Views/Shared/Components/{View Component Name}/{View Name} path.

Which makes me think that there is a way around this restriction, but it doesn't specify how that would work or what it would look like.

1

There are 1 best solutions below

0
On BEST ANSWER

Like Nic I agree that having several to dozens of files named default.cshtml is annoying. More so is having several to dozens of folders with just a single file in each folder

Components/ViewComponentName/default.cshtml  
Components/AnotherViewComponentName/default.cshtml  
Components/AThirdViewComponentName/default.cshtml  

et cetera

I understand the reasons for the recommended name and location...but I simply disagree and will accept the consequences. For those who share my cavalier attitude, View() allows you to specify a View name

return View("Schools", items);

or even to specify a path to the View if you put it in a non-standard location

return View("/Pages/Components/Schools.cshtml", items);

I'm using Razor Pages but I'm sure this works for Views/Shared/Components as well.