Getting the HTML for a ViewResult in ASP.NET Core

This is another post tagged “hack”: this time, how to get the HTML for a rendered view, in code. This is a standard solution that does not use any kind of reflection (or other) magic.

So, the idea is to pick up a ViewResult (it will also work for a PartialViewResult, but, alas, they do not share a common class – see #6984) and call some method, say, ToHtml, to get the rendered output. This method can look like this:

public static class ViewResultExtensions
{
public static string ToHtml(this ViewResult result, HttpContext httpContext)
{
var feature = httpContext.Features.Get<IRoutingFeature>();
var routeData = feature.RouteData;
var viewName = result.ViewName ?? routeData.Values["action"] as string;
var actionContext = new ActionContext(httpContext, routeData, new ControllerActionDescriptor());
var options = httpContext.RequestServices.GetRequiredService<IOptions<MvcViewOptions>>();
var htmlHelperOptions = options.Value.HtmlHelperOptions;
var viewEngineResult = result.ViewEngine?.FindView(actionContext, viewName, true) ?? options.Value.ViewEngines.Select(x => x.FindView(actionContext, viewName, true)).FirstOrDefault(x => x != null);
var view = viewEngineResult.View;
var builder = new StringBuilder();

using (var output = new StringWriter(builder))
{
var viewContext = new ViewContext(actionContext, view, result.ViewData, result.TempData, output, htmlHelperOptions);

view
.RenderAsync(viewContext)
.GetAwaiter()
.GetResult();
}

return builder.ToString();
}
}
To use it, just do:
var view = this.View(“ViewName”);
var html = view.ToHtml();
Have fun! Winking smile

                             

12 Comments

  • Thanks for this Ricardo!!

  • I was wondering if you could expand on your example and explain it in more detail.

    var view = this.View(“ViewName”);
    var html = view.ToHtml();

    Where does this code go, in a view result of an conroller?

    thanks,
    John

  • Hi, John!
    This code goes in an action method of a controller. The View method is inherited from the Controller class.
    What else do you need to know?
    Cheers

  • thanks for sharing

  • Sometime nothing work , need html in server side . i can remember render event of webform.


  • You can find other solutions to this problem here, for example if you need to pass a Model to the view:
    https://stackoverflow.com/questions/32558941/render-razor-view-to-string-in-asp-net-core

  • wobble: thanks for the heads up, but this requires a third-party library, RazorEngine. My solution, of course, also allows passing a model to the view, it just picks up any ViewResult object, which you can build any way you like.

  • Here another example, no 3rd party :)

    https://github.com/aspnet/Entropy/tree/dev/samples/Mvc.RenderViewToString

  • Hi, Vaclav!
    Thanks, it seems interesting!

  • I could not see any error in my work as I performed it with my one
    var view = this.View(“ViewName”);
    var html = view.ToHtml();
    Applied proper attributes and alignments but not fully sure what's wrong with it. Perhaps need to seek some seniors also.

  • Thanks,

    but the html generated is not binding the values with "asp-for"

    the following:
    <span>@Model.SomeID</span<
    <input type="hidden" asp-for="SomeID" />

    will be:
    <span>123</span>
    <input type="hidden" data-val="true" data-val-required="The SomeID field is required." id="SomeID" name="SomeID" value="0">






  • Hi, Dov!
    That's interesting - it seems that it is not respecting tag helpers. I will need to have a look.
    Thanks for the heads up!

Add a Comment

As it will appear on the website

Not displayed

Your website