In this post you will learn how can you customize the Razor View engine
Before reading this post, I expect you guys have some knowledge of ASP.Net MVC.
- Removing All the View Engines & registering the Razor Engine
Open the Global.asax file and write this code in the Application_Start,this function calls first when run the Application.
{
//Remove All View Engine including Webform and Razor
ViewEngines.Engines.Clear();
//Register Razor View Engine
ViewEngines.Engines.Add(new RazorViewEngine());
//Other code is removed for clarity
}
After removing the Web Form and other View engine as you noticed that Razor View engine looks up the C# views as shown below.
Now run the Application,you get this error on the browser after running the application.
As you know MVC is highly extensible hence you can completely replace the Razor view engine with a new custom razor engine. by doing so, this will slightly improve your application performance.
- Custom C# Razor View Engine
- public class CSharpRazorViewEngine : RazorViewEngine
- {
- public CSharpRazorViewEngine()
- {
- AreaViewLocationFormats = new[]
- {
- "~/Areas/{2}/Views/{1}/{0}.cshtml",
- "~/Areas/{2}/Views/Shared/{0}.cshtml"
- };
- AreaMasterLocationFormats = new[]
- {
- "~/Areas/{2}/Views/{1}/{0}.cshtml",
- "~/Areas/{2}/Views/Shared/{0}.cshtml"
- };
- AreaPartialViewLocationFormats = new[]
- {
- "~/Areas/{2}/Views/{1}/{0}.cshtml",
- "~/Areas/{2}/Views/Shared/{0}.cshtml"
- };
- ViewLocationFormats = new[]
- {
- "~/Views/{1}/{0}.cshtml",
- "~/Views/Shared/{0}.cshtml"
- };
- MasterLocationFormats = new[]
- {
- "~/Views/{1}/{0}.cshtml",
- "~/Views/Shared/{0}.cshtml"
- };
- PartialViewLocationFormats = new[]
- {
- "~/Views/{1}/{0}.cshtml",
- "~/Views/Shared/{0}.cshtml"
- };
- }
- }
- Regisering the C# Razor View Engine
- protected void Application_Start()
- {
- //Remove All View Engine including Webform and Razor
- ViewEngines.Engines.Clear();
- //Register C# Razor View Engine
- ViewEngines.Engines.Add(new CSharpRazorViewEngine());
- //Other code is removed for clarity
- }
No comments:
Post a Comment