Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using FindView in Orchard

Tags:

orchardcms

I'm trying to use:

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

as part of a process to render the contents of a view to send nice formatted emails. I'm using it inside an Orchard Controller. I have used similar code outside of Orchard in an MVC project and it works fine.

However in Orchard running this code fails to find the view I'm looking for and returns a view engine result that has searched 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?

like image 859
Richard Garside Avatar asked Dec 27 '22 16:12

Richard Garside


2 Answers

This answer is based on the advise given me by Bertrand, but I wanted to bring it together with what I'd discovered.

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

I then used the following code to resolve and render a 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();
    }
}
like image 175
Richard Garside Avatar answered Dec 31 '22 06:12

Richard Garside


I think you'll want to take a close look at Orchard.Framework/Mvc/ViewEngines, in particular IViewEngineProvider and ThemeAwareViewEngine. There's a lot more going on when in Orchard, such as themes, multi-tenancy, and a richer environment in general that may be needed to make this work. What's likely happening here is that the view engines don't have enough information to resolve a view and thus opt out of the chain. You might want to put a breakpoint into ThemeAwareViewEngine.FindView, and then inspect the private dependency fields of that class. I wouldn't be surprised if they were null, because getting to FindView through statics will probably not allow dependency injection to do its stuff properly. Then again I'm just guessing.

like image 29
Bertrand Le Roy Avatar answered Dec 31 '22 07:12

Bertrand Le Roy