0

Problem: I need to render a Razor Page partial to a string and use Render a Razor Page to string but Layout not used during rendering page.

public async Task<string> RenderToStringAsync(string pageName, object model, CancellationToken cancellationToken)
{
    var actionContext =
         new ActionContext(
              _httpContext.HttpContext,
              _httpContext.HttpContext.GetRouteData(),
              _actionContext.ActionContext.ActionDescriptor
         );

    using (var sw = new StringWriterWithEncoding(Encoding.UTF8))
    {
        var result = _razorViewEngine.FindPage(actionContext, pageName);

        if (result.Page == null)
        {
            throw new RazaorPageNotFoundException($"The page {pageName} cannot be found.");
        }

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


        var viewContext = new ViewContext(
             actionContext,
             view,
             new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
             {
                 Model = model
             },
             new TempDataDictionary(
                  _httpContext.HttpContext,
                  _tempDataProvider
             ),
             sw,
             new HtmlHelperOptions()
        );


        var page = ((Page)result.Page);
        
        page.PageContext = new PageContext
        {
            ViewData = viewContext.ViewData,
            HttpContext = _httpContext.HttpContext,
        };

        page.ViewContext = viewContext;

        _activator.Activate(page, viewContext);

        await page.ExecuteAsync();

        return sw.ToString();
    }
}

        

Page code (for test):

@page
@{
    Layout = "~skins/_desktop/Views/Layouts/Standart.cshtml";
}
<div>test</div>

Layout code (for test):

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <div class="demo-overlay"></div>
    <!-- Wrapper -->
    <div class="page-wrapper-common">
        @RenderBody()
    </div>
</body>
</html>

After rendering page (no layout):

<div>test</div>

I try:

  • constant and relative path to layout,
  • explicit set page.IsLayoutBeingRendered and page.Layout
Robert
  • 2,407
  • 1
  • 24
  • 35
Shadow76
  • 61
  • 5

0 Answers0