如何剃刀视图转换为字符串?剃刀、视图、字符串、转换为

2023-09-03 02:33:06 作者:宠你到老

我想用我的剃须刀认为是某种模板用于发送电子邮件, 所以我想拯救我的模板看来,念给控制器作为字符串,执行necessarry替换,然后发送。 我有解决方案,工程,模板某处托管为HTML页面,但我想将它放在我的应用程序,例如考虑,但不知道如何读视图字符串控制器?

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 view, read it in controller as string, do necessarry replacements, then send it. I have solution that works, template is hosted somewhere as html page, but I would like to put it in my application, i.e. in view but don't know how to read view as string in controller?

推荐答案

我用下面的。把你的基本控制器,如果你有一个,这样你可以访问它的所有控制器。

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