Can I interleave two MVC view engines when searching for views?

一笑奈何 提交于 2019-12-11 04:11:45

问题


I'm using the WebForms and Razor view engines in my MVC project. They work just fine together. However, I have an inheritance-based project set up, such that I have multiple child projects derived from a base project. With just one view engine, this works such that MVC will search for a view in the child projects, and failing to find it, it will search the base.

However, when adding the second view engine, this search pattern is broken, such that the WebForms engine searches the child and then the base, and then the Razor engine searches the child and then the base. As such, a base .aspx view will be given priority over a child .cshtml view. In other words, when searching for a view named MyView, this is the prioritized list of locations searched:

Child\MyView.aspx
Base\MyView.aspx
Child\MyView.cshtml
Base\MyView.cshtml

What I want is to have the two engines each check the child projects before either checks the base project, as such:

Child\MyView.aspx
Child\MyView.cshtml
Base\MyView.aspx
Base\MyView.cshtml

Is this possible, and if so, can someone point me in the right direction?


回答1:


You could write your own view engine that uses both existing view engines internally.

public InterleavedViewEngine : IViewEngine
{
    public string[] SearchLocations;

    RazorViewEngine _razor;
    WebFormsViewEngine _webForms;

    public override ViewEngineResult FindView(...)
    {
        //iterate search paths, trying Razor, then WebForms, etc...
        foreach(var location in SearchLocations)
        {
            var razorResult = _razor.FindView(...);

            if(razorResult.View == null)
            {
               //web forms, etc... here
            }

        }
    }

}


来源:https://stackoverflow.com/questions/7854842/can-i-interleave-two-mvc-view-engines-when-searching-for-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!