且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将Razor视图转换为字符串?

更新时间:2023-02-16 21:49:46

我使用以下内容.如果有的话,将其放在基本控制器上,这样就可以在所有控制器中访问它.

I use the following. Put it on your base controller if you have one, that way you can access it in all controllers.

public static string RenderPartialToString(Controller controller, string viewName, object model)
{
    controller.ViewData.Model = model;

    using (StringWriter sw = new StringWriter())
    {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
        viewResult.View.Render(viewContext, sw);

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