Using FindView in Orchard

跟風遠走 提交于 2019-12-01 19:23:51

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.

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