Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

1.4 KB
Raw Blame
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace Grand.Web.Common.Controllers;

public static class ControllerExtensions
{
    public static async Task<string> RenderPartialViewToString<TModel>(this Controller controller, string viewName,
        TModel model, bool partial = false)
    {
        if (string.IsNullOrEmpty(viewName)) viewName = controller.ControllerContext.ActionDescriptor.ActionName;

        controller.ViewData.Model = model;

        await using var writer = new StringWriter();
        IViewEngine viewEngine =
            controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
        if (viewEngine == null) return writer.GetStringBuilder().ToString();
        var viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);

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

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

        await viewResult.View.RenderAsync(viewContext);

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