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?
Layout pages are typically named _Layout. cshtml, the leading underscore preventing them from being browsed directly.
A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.
A partial view is like as user control in Asp.Net Web forms that is used for code re-usability. Partial views helps us to reduce code duplication. Hence partial views are reusable views like as Header and Footer views.
In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.
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.
It is only a naming convention that partial views should start with underscore. but strangely /mvc engine doesn't search for partial views with underscore.
return PartialView("_Create")
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With