Pages

Tuesday, January 24, 2012

Custom ViewEngine in MVC


When application start in MVC, framework first look for view in views folder. If its unable to find there then it will go for shared folder. If its still unable to find view over there then it will throw an error. By default MVC firstly look into views folder then shared folder.
Like this we can also create our own custom folder and give functionality to look on that folder too. MVC provide a class under framework "WebFormViewEngine" which is responsbile for finding views.
In order to set custom folder functionality first create a folder in Views folder then override a method "FindView" which is provided in WebFormViewEngine.

The first thing we are going to do to create our custom ViewEngine, is define the paths that we want to use for our master pages, view pages, and shared pages.


 //Master Pages:
 ~/Templates
 it use to be ~/Views/Shared or the controllers view
 //View Pages:
 ~/Views
 //Shared Pages:
 ~/Common
 it use to be ~/Views/Shared

public SimpleViewEngine ()
{
 /* {0} = view name or master page name
 * {1} = controller name
 */
 // create our master page location
 MasterLocationFormats = new[] {
 "~/Templates/{0}.master"
} //create our views and common shared locations ViewLocationFormats = new[] { "~/Views/{1}/{0}.aspx", "~/Common/{0}.aspx", }; //create our partial views and common shared locations PartialViewLocationFormats = new[] { "~/Views/{1}/{0}.ascx", "~/Common/{0}.ascx" }; } //Global.asax, similar to the same way we register new routes. public static void RegisterViewEngines(ViewEngineCollection viewEngines) { viewEngines.Clear(); viewEngines.Add(new SimpleViewEngine()); } public static void RegisterRoutes(RouteCollection routes) { ... } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); RegisterViewEngines(ViewEngines.Engines); }

No comments:

Post a Comment