How does ASP.NET MVC arbitrage between two identically named views (aspx and razor)?

Using ASP.NET MVC3, I created a new Razor view and gave it the same name as the existing .aspx view I used. I noticed that the controller continued to look up .aspx (which has the same name as the action), which pretty much matches what was expected. Then I renamed the .aspx view and the action, getting the razor.cshtml view.

So, if I have two views, called myview.aspx and myview.cshtml, and an action called MyView () that returns return View (), it will display the view myview.aspx and return it.

How did MVC3 decide which view type to use by default? Is there a way to change this default behavior to prefer a razor view over the .aspx view?

+4
source share
2 answers

It all depends on the order in which the engines are viewed in the ViewEngines.Engines collection. Here's what the static ViewEngines constructor looks like (as shown in Reflector in RTM MVC 3):

 static ViewEngines() { ViewEngineCollection engines = new ViewEngineCollection(); engines.Add(new WebFormViewEngine()); engines.Add(new RazorViewEngine()); _engines = engines; } 

which explains why WebForms is the preferred view engine.

So, you can perform the following grotesque hack in Application_Start to invert Razor preference :-)

 var aspxVe = ViewEngines.Engines[0]; var razorVe = ViewEngines.Engines[1]; ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(razorVe); ViewEngines.Engines.Add(aspxVe); 
+4
source

I would suggest that this is not the order in which view engines are registered. Initially, previously registered scan engines will be requested. If you want to reorder:

 ViewEngines.Engines.Insert(0, ...); 
+1
source

Source: https://habr.com/ru/post/1335896/


All Articles