Overriding MVC 4.0 ViewEngine

不问归期 提交于 2019-12-11 04:59:10

问题


I want to have different views in different directories (NOT AREAS!) so that when the URL contains a certain string , the viewEngine will result serving the another view (same name) from a different directory.

The Code is here:

 public class CheckinViewEngine : WebFormViewEngine
{
    public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
    {
        ViewEngineResult result;

       var routData = controllerContext.RequestContext.RouteData.Values;

       if (controllerContext.RequestContext.HttpContext.Request.Path.ToUpper().Contains("UP"))
       {
         result=  base.FindView(controllerContext, "Home/Up/" + viewName, masterName, useCache);
       }
       else
       {
          result=  base.FindView(controllerContext, viewName, masterName, useCache);
       }
        return result;
    }    

}

In this case I check that the URL contains "UP".

In Global.asax I've added:

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CheckinViewEngine ());

My problems are so: the ViewEngineResult.View is null and also, upon any request I get infinite loop request for this method.

Any Idea?


回答1:


1) I would add the 'special' location that you are wanting to find views in. See here:

Can I specify a custom location to "search for views" in ASP.NET MVC?

2) Then for the views that you want to be located in that folder and used when your 'special' url words are found, add them there but with .up (or whatever) in the view's filename. So if it is normally Index.cshtml add one called Index.Up.cshtml. (You can skip the first step if you are more just interested in rendering a view based on your 'special' word.

3) Then in your FindView method, do your test for the url and if found, rename the view name to the .Up version so the view engine can find it.



来源:https://stackoverflow.com/questions/20071809/overriding-mvc-4-0-viewengine

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