Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: When should I create custom View Engine

I know what View Engine is, I preferred to use Razor view engine just because of its simple syntax over ASPX engine. Inbuilt view engine performs almost all task for you, then in what scenario I should create my own view engine,

I googled it but getting answers for How to create it and not when and why to create it.

Can any one help me to describe the real time scenario?

like image 972
kiran Avatar asked Oct 24 '15 06:10

kiran


1 Answers

For example, you can change the view files locations that Razor searches with the help of custom view engine.

Normally, in MVC these locations are searched for partial views:

 // 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 LayoutsPartialViews folder to Shared folder and add partial views which for example will be used only for layouts. And add for example ColorfuleHeader.cshtml to that location. And try to render that view via this:

  @Html.Partial("ColorfulHeader");

Such exception will be throwned:

The partial view 'ColorfulHeader' was not found or no view engine supports the searched locations. The following locations were searched...:

So we must add this location to the searched locations. And for doing this we must create our custom view 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 action invoker goes to each view engine in turn to see if a view can be found. By the time that we are able to add our view to the collection, it will already contain the standard Razor View Engine. To avoid competing with that implementation, we call the Clear method to remove any other view engines that may have been registered, and then call the Add method to register our custom implementation.

ViewEngines.Engines.Clear(); 
ViewEngines.Engines.Add(new CustomLocationViewEngine()); 
like image 75
Farhad Jabiyev Avatar answered Oct 26 '22 15:10

Farhad Jabiyev