Render Razor View or Partial to String #37187
Labels
area-mvc
Includes: MVC, Actions and Controllers, Localization, CORS, most templates
design-proposal
This issue represents a design proposal for a different issue, linked in the description
Summary
I recently wanted to render a Razor page or partial to a string programmatically, and I've written a pretty good way to get it done by combining several solutions I've seen around the Web and testing them for performance. I'd like to contribute my solution to ASP.NET Core. It's an extension to HttpContext since it requires HttpContext's RequestServices.
Motivation and goals
This allows me to render a Razor partial to a string. It's especially useful for outputting HTML to be emailed.
In scope
Email a Razor view
Out of scope
Unknown
Risks / unknowns
@page
at the top. It only seems to work with partials (no@page
). Specifically, Model is null on the .cshtml page if it contains@page
at the top. Again, this does not occur when no@page
is at the top. I would like someone to provide a suggestion about that please.Examples
It is invoked like this:
string html = await HttpContext.RenderViewAsync("Pages/SomePage.cshtml", new SomePageModel("X"), isMainPage: false);
I've attached the source code file. I couldn't attach a plain .cs file because GitHub apparently does not allow them to be uploaded in an issue.
ViewRendererHttpContextExtensions.zip
The text was updated successfully, but these errors were encountered: