Using FindView in Orchard

I am trying to use:

var viewEngineResult = ViewEngines.Engines.FindView(ControllerContext, myViewName, null); 

as part of a process for visualizing the contents of a presentation to send messages with good formatted email. I use it inside an Orchard controller. I used the same code outside of Orchard in the MVC project and it works great.

However, in Orchard, this code cannot find the view I'm looking for and returns the result of a viewer that searched for 0 locations.

viewEngineResult has the following values ​​after it is called:

  • SearchedLocations: Count = 0,
  • View: null,
  • ViewEngine: null

Is there a reason this doesn't work in Orchard, and is there a way to make it work?

+4
source share
2 answers

I think you should take a look at Orchard.Framework / Mvc / ViewEngines, specifically IViewEngineProvider and ThemeAwareViewEngine. There is much more going on when Orchard, for example, has themes, multi-tenant rentals, and a richer environment in general that might be needed to do the job. Probably, what happens here is that in the viewing mechanisms there is not enough information to resolve the presentation and, therefore, abandon this chain. You might want to set a breakpoint in ThemeAwareViewEngine.FindView, and then view the private dependency fields of this class. I would not be surprised if they were null, because getting into FindView via statics would probably not allow dependency injection to do their stuff correctly. Again, I just guess.

+4
source

This answer is based on the advice Bertrand gave me, but I wanted to put it together with what I found.

In order to be able to use FindPartialView, I needed to inject an instance of IViewEngineProvider into my controller.

Then I used the following code to resolve and render the view:

 private String RenderView(String viewName, object model) { var paths = new List<string>(); // This can just be an empty list and it still finds it. var viewEngine = _viewEngineProvider.CreateModulesViewEngine(new CreateModulesViewEngineParams {VirtualPaths = paths}); var viewResult = viewEngine.FindPartialView(ControllerContext, viewName, false); if (viewResult.View == null) { throw new Exception("Couldn't find view " + viewName); } var viewData = new ViewDataDictionary {Model = model}; using (var sw = new StringWriter()) { var viewContext = new ViewContext(ControllerContext, viewResult.View, viewData, TempData, sw); viewResult.View.Render(viewContext, sw); return sw.GetStringBuilder().ToString(); } } 
+6
source

All Articles