Priority of razor views over the aspx in mixed MVC

2019-07-26 14:05发布

问题:

I've converted old MVC2 project to MVC3. Now I have .aspx views along with razor .cshtml.

Let's say I have a view associated with controller (HomeController, Index action and ~\Views\Home\Index.aspx) and at the same time I still have absolutely different ~\Views\Shared\Index.aspx.

Normally when Index Action calls View() it renders ~\Views\Home\Index.aspx. But if I convert the view into razor view, the same action instead of rendering ~\Views\Home\Index.cshtml calls ~\Views\Shared\Index.aspx.

So I guess MVC gives priority to .aspx pages rather to .cshtml. Maybe I need to change something in web.config files, because now I have to explicitly tell it which view to get:

View("~\Views\Home\Index.cshtml")

Even if I drop the extension View("~\Views\Home\Index") it will still call the shared .aspx view, although I have the right path. Strange isn't it?

回答1:

The problem you are having is the default priority of MVC views. Here is the default:

~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml 

As you can see, it favors all aspx/ascx files, even in the shared directory, before similar razor views.

One solution is to Get MVC Razor favor .cshtml over .aspx, however this solution does NOT reassociated the aspx/ascx files. So you'd need something like:

protected void Application_Start() 
{ 
  ViewEngines.Engines.Clear(); 
  ViewEngines.Engines.Add(new RazorViewEngine()); 
  ViewEngines.Engines.Add(new WebFormViewEngine()); 
}