C# 在运行时动态生成 Razor 视图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9703119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically Produce Razor Views at Runtime?
提问by Joshua Enfield
I am looking at building a web configurable layout engine, and would like to directly use the razor engine under the hood.
我正在考虑构建一个 Web 可配置的布局引擎,并想直接使用引擎盖下的剃刀引擎。
Lets say I have some information available via classes, xml, or a database - I want to convert that into native razor code at runtime(by this I mean to imply my source of defining content and structure is based on a provider model). Rather than convert an xml file or something on the fly every request I figured I might as well just write Razor, and let that view engine take care of everything.
假设我有一些通过类、xml 或数据库可用的信息 - 我想在运行时将其转换为本机 razor 代码(我的意思是暗示我定义内容和结构的来源基于提供者模型)。与其在每个请求中即时转换 xml 文件或其他内容,我想我还不如编写 Razor,让视图引擎处理所有事情。
Can I plug razor code directly into the engine from a source that is not the file system?
我可以将 razor 代码从非文件系统的来源直接插入引擎吗?
Will there be any gotchas if I dynamically generate .cshtml views and layouts into files at run-time [and dynamically set those views in the controller actions]?
如果我在运行时动态生成 .cshtml 视图和布局到文件中[并在控制器操作中动态设置这些视图],会有任何问题吗?
采纳答案by Nick Bork
It is possible to do. Razor will have some more gotcha moments than classic Webforms view engine but here are some resources:
这是可能的。Razor 将比经典的 Webforms 视图引擎有更多的问题,但这里有一些资源:
http://rebuildall.umbraworks.net/2009/11/17/ASP_NET_MVC_and_virtual_views
http://rebuildall.umbraworks.net/2009/11/17/ASP_NET_MVC_and_virtual_views
Using custom VirtualPathProvider to load embedded resource Partial Views
使用自定义 VirtualPathProvider 加载嵌入资源 Partial Views
Storing ASP.Net MVC Views in the Database
ASP.NET MVC load Razor view from database
You'll be creating a custom ViewEngine that will determine where to look for the views. Views can be stored on the file system, in the database or as an embedded resources. Read up on the links I provided and it should get you going!
您将创建一个自定义 ViewEngine,它将确定在何处查找视图。视图可以存储在文件系统、数据库中或作为嵌入式资源。阅读我提供的链接,它应该会让你开始!

