如何剃刀视图转换为字符串? [英] How to convert razor view to string?

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

问题描述

我想用我的剃须刀认为是某种模板用于发送电子邮件, 所以我想拯救我的模板看来,念给控制器作为字符串,执行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();
    }
}

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

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