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();
}
}
The main difference between my article which you linked to, and your code is that in my example, the
RenderViewAsyncequivalent method isasyncand returns aTask<string>, and the call toRenderAsyncis 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
asyncand return aTask<string>:Then await the
RenderAsyncmethod call in the last but one line: