Overriding MVC 4.0 ViewEngine

2019-08-03 05:03发布

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条回答
Anthone
2楼-- · 2019-08-03 05:56

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.

查看更多
登录 后发表回答