Custom View Engine in ASP.NET MVC.

You do not need to create Custom View Engine for most projects. The reason for using Custom View Engine is to change the default views location at run-time. The MVC Framework has two built-in view engines – Razor and WebForms. View engines implement IViewEngine interface:

namespace System.Web.Mvc
{
    public interface IViewEngine
    {
        ViewEngineResult FindPartialView(ControllerContext controllerContext,
        string partialViewName, bool useCache);
        ViewEngineResult FindView(ControllerContext controllerContext,
        string viewName, string masterName, bool useCache);
        void ReleaseView(ControllerContext controllerContext, IView view);
    }
}

Let’s say you need to store most views in GeneralComponents folder. So you have to extend view engine for searching not only in “ControllerName” and Shared folders but also in GeneralComponents folder. Assume that you have Home cotroller and it has About action. In the Views folder you have Home folder that stores views related to Home controller. If you move this view to GeneralComponents folder you see the follwing error:

view-not-found

 

In order to allow view engine search in GeneralComponents folder you need to implement custom RazorViewEngine.

 

public class MyRazorViewEngine : RazorViewEngine
{
    public MyRazorViewEngine()
    {

        ViewLocationFormats = new[] {
            "~/Views/%1/{1}/{0}.cshtml",
            "~/Views/%1/{1}/{0}.vbhtml",
            "~/Views/%1/Shared/{0}.cshtml",
            "~/Views/%1/Shared/{0}.vbhtml",
            "~/Views/GeneralComponents/{0}.cshtml",
            };

        PartialViewLocationFormats = new[] {
            "~/Views/%1/{1}/{0}.cshtml",
            "~/Views/%1/{1}/{0}.vbhtml",
            "~/Views/%1/Shared/{0}.cshtml",
            "~/Views/%1/Shared/{0}.vbhtml",
             "~/Views/Shared/{0}.cshtml",
            };
    }
}

Then register MyRazorViewEngine in Application_Start()

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyRazorViewEngine());

Now the About view is found by our ViewEngine.

Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this