How to render full RazorPage to string?

倖福魔咒の 提交于 2020-07-23 06:38:43

问题


I tried to use the solution from https://stackoverflow.com/a/54043063/234954, to render a page as a string (so I can turn it into a PDF), but that only gets me the main view, it doesn't get the layout associated with the page (and so it is missing the style sheets and some header/footers).

How can I render the full page as a string, and not just the partial view?


回答1:


I used this article code in a recent project to render html to feed into PDF generation.

I used templates in the Views folder so not razor pages.

It works with Layouts and partials in templates.

https://ppolyzos.com/2016/09/09/asp-net-core-render-view-to-string/




回答2:


I found that I could get what I wanted (the whole page) by making two changes to the answer I was looking at:

var view = new RazorView(_razorViewEngine,
                _activator,
                new List<IRazorPage>(),
                page,
                HtmlEncoder.Default,
                new DiagnosticListener("ViewRenderService"));

changed to :

 var view = new RazorView(_razorViewEngine,
                _activator,
                pageModel.PageContext.ViewStartFactories.Select(v => v()).ToList(),
                page,
                HtmlEncoder.Default,
                new DiagnosticListener("ViewRenderService"));

and

await page.ExecuteAsync();

to

await view.RenderAsync(viewContext);

Note that if the viewstart pages aren't included in the view, then rendering the view produces the same as executing the page.



来源:https://stackoverflow.com/questions/62584735/how-to-render-full-razorpage-to-string

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