How does RenderPartial figure out where to find a view?

Ok Probably Google is not working, and I recall it a while ago, but I can not find it.

I have a view and a partial view in different directories. In the view, I say @Html.RenderPartial("[partial view name]"); how does RenderPartial figure out where to look? It should be a convention, but what is it?

My opinion is in the WebRoot\Views\Admin\ folder and partially located in WebRoot\Views\Admin\Partials

Not sure if this is configured correctly.

I am using MVC 3 (Razor engine)

+4
source share
4 answers

you can, but you need to register routes to tell the view engine where to look. For example, in Global.asax.cs you will have:

 ViewEngines.Engines.Add(new RDDBViewEngine()); 

and class:

 public class RDDBViewEngine : RazorViewEngine { private static string[] NewPartialViewFormats = new[] { "~/Views/Shared/Partials/{0}.cshtml" , "~/Views/{0}.cshtml" }; public RDDBViewEngine() { base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray(); } } 

{0} for all subfolders with partial.

+4
source

The localization of views depends on the ViewEngine object. WebFormViewEngine was the one originally shipped with MVC 1, and you can see the paths it is looking for in codeplex . Note that he is looking for the same paths for representations and partial representations.

CshtmlViewEngine (Razor) introduced with MVC 3 (or rather WebMatrix) looks for similar locations, but looks for different extensions.

+3
source

Each view engine registered in your application has a list of file templates that will be executed when accessing the view using a simple name (you can also link to it using the full path, for example ~\Views\Admin\View.aspx )

In MVC 3, the properties of the viewer define the patterns to search (this applies to the Razor and WebForms viewers).

+1
source

Instead of subclassing RazorView (as suggested by zdrsh), you can simply modify the existing RazorViewEngine PartialViewLocationFormats property. This code is in Application_Start:

 System.Web.Mvc.RazorViewEngine rve = (RazorViewEngine)ViewEngines.Engines .Where(e=>e.GetType()==typeof(RazorViewEngine)) .FirstOrDefault(); string[] additionalPartialViewLocations = new[] { "~/Views/[YourCustomPathHere]" }; if(rve!=null) { rve.PartialViewLocationFormats = rve.PartialViewLocationFormats .Union( additionalPartialViewLocations ) .ToArray(); } 
+1
source

Source: https://habr.com/ru/post/899012/


All Articles