MVC3 WebFormViewEngine or CshtmlViewEngine

In my previous blog, I made the following statement:

Turns out ascx has a higher priority than cshtml. Seems like the View Engine looks for .ascx files first and then searches for the .cshtml files. MVC team, please let me know if my understanding is wrong.

Not the MVC team, but Paul Vencill commented that it was just the order of registering the view engines that decided whether to pick up the .ascx or the .cshtml views.

This made sense, and to test it I put a breakpoint in the Application_Start event in the Global.asax file.

image1

The ViewEngines is a static class and the Engines property is basically an enumerable of IViewEngine types. From the above image, we see that the WebFormViewEngine (the default MVC ViewEngine) is registered before the CshtmlViewEngine (Razor’s ViewEngine).

Per Paul’s comments, I decided to change this to something like below:

   1: protected void Application_Start()
   2: {
   3:     AreaRegistration.RegisterAllAreas();
   4:  
   5:     ViewEngines.Engines.Clear();
   6:     ViewEngines.Engines.Add(new CshtmlViewEngine());
   7:     ViewEngines.Engines.Add(new WebFormViewEngine());
   8:  
   9:     RegisterGlobalFilters(GlobalFilters.Filters);
  10:     RegisterRoutes(RouteTable.Routes);
  11: }

 

Using the same sample application that I used in my previous blog, I get the following output with the above changes:

image6_3F812C6A[1]

If you’ve gone through the MVC 3 - first look article, you’ll know that this uses the .cshtml view to display the components section.

With this, you can also register other view engines (like spark or nhaml) or unregister the ones you do not want. You can say that you want Cshtml to be the only view engine in your project even though you created the (ASPX) version of MVC 3 application.

Verdict: Yet another dimension in which MVC allows customization – brilliant!

2 Comments

Comments have been disabled for this content.