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
RenderViewAsync
equivalent method isasync
and returns aTask<string>
, and the call toRenderAsync
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 aTask<string>
:Then await the
RenderAsync
method call in the last but one line: