[MVC]Customizing ViewEngine in ASP.NET MVC



In an ASP.NET MVC application the request URI is of the following format {controller}/{action}/{id}.Based on the controller name in the URI the ControllerFactory instantiates the appropriate Controller class and then based on the action in the URI the corresponding action method in the Controller is executed.Action method then dispatches the right view and by default the location of the views are in the path ~/Views/<Controller>/<Action>.aspx.But how can we change this default behavior and make the location of the view configurable based on Web.config settings.

This can be done very easily by overriding the FindView method of System.Web.Mvc.VirtualPathProviderViewEngine.In my previous post I have discussed in details about the Classes and Interfaces related to View Engines and how views are located.So we have create a class inheriting System.Web.Mvc.WebFormViewEngine and then override the FindView method as shown below:

public  class CustomViewEngine:WebFormViewEngine
     public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName)
         string viewPath = string.Empty;
         string masterPath = string.Empty;
         ViewEngineResult result = null;

         if (controllerContext == null) throw new ArgumentNullException("ControllerContext cannot be null");
         if (viewName == null || viewName.Length == 0) throw new ArgumentNullException("ViewName cannot be null");

        //Read View Path from Web.config

         viewPath = ConfigurationManager.AppSettings[viewName];
         if (viewPath == null || viewPath.Length == 0) throw new ConfigurationErrorsException("View Path cannot be null or empty.Please check web.config");
         masterPath = ConfigurationManager.AppSettings[masterName];

       //Create an instance of IView and wrap the results in an ViewEngineResult instance

         result = new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);
         return result;


Now we need to remove the default view engine and plug in our custom view engine in Application_Start event of Global.asax.cs as follows:

ViewEngines.Engines.Add(new SB.Web.Mvc.CustomViewEngine());

Lastly we need to add the actual view paths in web.config as shown below:

<add key="Index" value="~/Pages/Index.aspx"/>
<add key="About" value="~/Pages/About.aspx"/>

赞(0) 打赏
分享到: 更多 (0)