问题描述
我在网站上搜索了很多,但我能找到的只是关于如何呈现部分控件 .ascx
或依赖于控制器上下文的示例.
I've been searching the site a lot, but all I could find were examples on how to render partial controls .ascx
, or depended on a controller context.
我想要一种方法,使我能够仅提供视图的相对路径和模型,并将该视图与该模型渲染为字符串:
I want a method that enables me to provide just the relative path to the view, and a model, and render that view with that model into a string:
string result = Utility.RenderViewToString("~/Views/My/Profile.cshtml", model);
我能找到的所有例子要么是针对旧版本的 MVC,要么就是没有做我在这里需要做的事情.
All the examples I could find were either for older versions of MVC, or simply didn't do what I need to do here.
推荐答案
您可以使用 razorengine 实现这一点.
You can achieve that with the razorengine.
string template = "Hello @Model.Name! Welcome to Razor!";
string result = Razor.Parse(template, new { Name = "World" });
并且它不依赖于控制器上下文 - 但因此您无法使用 Html 助手(依赖于 http 上下文).但是使用razor作为字符串的模板引擎是完美的.
And it does not rely on the controller context - but because of that you are not able to use the Html helpers (which rely on the http context). But it is perfect to use razor as a template engine for strings.
这篇关于如何在 ASP.NET MVC 3 中将 Razor 视图呈现为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!