PartialView() does not return a View with a underscore

asp.net-mvc-4, asp.net-mvc-partialview

Solution

This answer is specifically for ASP.NET MVC5. It may require slight modification to work with other version of MVC but it should generally be applicable.

To have `return Partial(model)` respect underscores on partial names, you need a custom view engine. Fortunately this is an exceedingly trivial custom view engine.

public class CustomRazorViewEngine : RazorViewEngine
{
    public CustomRazorViewEngine()
    {
      var underScored = new[] { "~/Views/{1}/_{0}.cshtml", "~/Views/{1}/_{0}.vbhtml" }

      PartialViewLocationFormats = underScored.Union(PartialViewLocationFormats).ToArray();
    }
}

The following format is the default patterns for Shared views:

~/Views/Shared/{0}.cshtml
~/Views/Shared/{0}.vbhtml

You could include alternates for these too if you wish. If you specifically want to only serve files with the underscore, remove the union and merely use: `PartialViewLocationFormats = underScored;`

This is with the razor view engine, I assume it would be comparable with the webforms view engine if that's your engine of choice.

Lastly you need to register this to be the view engine:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        //View Engines
        ViewEngines.Engines.Remove(ViewEngines.Engines.Single(x => x is RazorViewEngine));
        ViewEngines.Engines.Add(new CustomRazorViewEngine());

The `Startup` class is specific to MVC5, this would vary slightly between versions. You could use App_Start files with webactivator or the global.asax in other versions.

Problem

TemplateController: this works: ``` return PartialView("_Create"); ``` but this does not work: ``` return PartialView(); ``` The asp.net mvc convention should actually check a View folder with the name of the controller => "Template" and check for a View the same name as the action => "Create". This is valid for a return View(). Why does a return PartialView() not just consider the underscore?

Original source