Search code examples
c#asp.net-corerazor-pagesviewengine

How to write RenderViewToString in ASP.NET Core


I m using this method for render view in ASP.NET core. But it returns empty. What is the reason? Please help me. I tried different ways like this link https://www.learnrazorpages.com/advanced/render-partial-to-string it didnt work

    protected string RenderViewAsync(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
        {
            viewName = ControllerContext.ActionDescriptor.ActionName;
        }

        ViewData.Model = model;

        using (var writer = new StringWriter())
        {
            IViewEngine viewEngine = HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
            ViewEngineResult viewResult = viewEngine.FindView(ControllerContext, viewName, false);

            if (viewResult.Success == false)
            {
                return $"A view with the name {viewName} could not be found";
            }

            ViewContext viewContext = new ViewContext(
                ControllerContext,
                viewResult.View,
                ViewData,
                TempData,
                writer,
                new HtmlHelperOptions()
            );

            viewResult.View.RenderAsync(viewContext);

            return writer.GetStringBuilder().ToString();
        }
    }

Solution

  • The main difference between my article which you linked to, and your code is that in my example, the RenderViewAsync equivalent method is async and returns a Task<string>, and the call to RenderAsync is awaited. If you don't await an asynchronous method call, the program continues to operate as if nothing has happened. You never get the result of the operation.

    Try changing the method signature to make it async and return a Task<string>:

    protected async Task<string> RenderViewAsync(string viewName, object model)
    

    Then await the RenderAsync method call in the last but one line:

    await viewResult.View.RenderAsync(viewContext);