ASP.NET MVC: When Should I Create a Custom Viewer

I know what the View Engine , I preferred to use the Razor viewer only because of its simple syntax over the ASPX engine. The built-in viewing engine performs almost the entire task for you, in which scenario should I create my own viewing engine,

I googled, but I get answers to the question of how to create it, and not when and why to create it.

Can someone help me describe a real-time scenario?

+5
source share
1 answer

For example, you can change the location of the view files that Razor is looking for using a custom view engine.

Typically, in MVC, partial views are viewed in these places:

  // Part of the RazorViewEngine implementation from the Asp.net MVC source code PartialViewLocationFormats = new[] { "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml" }; 

Then add, for example, the LayoutsPartialViews folder to the Shared folder and add partial views, which, for example, will be used only for layouts. And add, for example, ColorfuleHeader.cshtml to this place. And try to make this view through this:

  @Html.Partial("ColorfulHeader"); 

Such an exception will be thrown:

Partial view of "ColorfulHeader" not found or not viewer supports found locations. The following places were searched ...

Therefore, we must add this location to the locations you find. And for this we must create our own viewing engine:

  public class CustomLocationViewEngine : RazorViewEngine { public CustomLocationViewEngine() { PartialViewLocationFormats = new[] { "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml", "~/Views/Shared/LayoutsPartialViews/{0}.cshtml", "~/Views/Shared/LayoutsPartialViews/{0}.vbhtml", }; } } 

Also, remember that the caller accesses each viewing engine, in turn, to see if it can be viewed. From a time when we can add our look to the collection, it will already contain the standard Razor View Engine. To avoid competition with this implementation, we call the Clear method to remove any other view engines that could be registered, and then call the Add method to register our custom implementation.

 ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new CustomLocationViewEngine()); 
+7
source

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


All Articles