如何将Razor视图转换为字符串? [英] How do you convert a Razor view to a string?

查看:120
本文介绍了如何将Razor视图转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Razor视图用作发送电子邮件的模板, 所以我想在视图中保存"模板,将其作为字符串读入控制器,进行一些必要的替换,然后发送.

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 necessary replacements, and then send it.

我有一个可行的解决方案:我的模板作为HTML页面托管在某个地方,但我想将其放入我的应用程序中(即,在我看来).我不知道如何在控制器中以字符串形式读取视图.

I have solution that works: my template is hosted somewhere as an HTML page, but I would like to put it into my application (i.e. in my view). I don't know how to read a view as a string in my 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();
    }
}

这篇关于如何将Razor视图转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆