How do you convert a Razor view to a string?

前端 未结 2 1915
终归单人心
终归单人心 2021-02-05 19:19

I would like to use my Razor view as some kind of template for sending emails, so I would like to \"save\" my template in a view, read it into controller as a string, do some ne

2条回答
  •  孤城傲影
    2021-02-05 20:00

    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();
        }
    }
    

提交回复
热议问题