c# - 如何从模型属性显示 Cshtml?ASP.NET 核心 MVC
问题描述
我认为我的问题希望有点简单。使用 ASP.NET Core MVC 和 Visual Studio。
我有一个将存储 cshtml 的数据库。我将把它读入index.cshtml
文件顶部的模型属性中。
对于某些部分,如果我只是将它放在 cshtml 文件中,我需要显示它会呈现的样子。
使用这个工程,大部分 -->@Html.Raw(Model.htmlcontent)
但是,所有@Model.Property
位都像这样显示,而不是像我想要的那样实际插入值。
有没有像 Html.Raw 这样的另一种方法可以做到这一点,或者是一个好的方法?
谢谢
解决方案
您将剃刀视图存储在数据库中,因此您需要首先将剃刀代码编译为实际的 html 代码,然后使用 @Html.Raw() 显示带有样式的 html 代码。
如果只想显示模型属性,可以使用仅支持 .net 5的RazorEngineCore库:
模型:
public class RazorModel
{
public string htmlcontent { get; set; }
}
public class TestModel
{
public string Name { get; set; }
public int[] Items { get; set; }
}
看法:
@model RazorModel
@Html.Raw(Model.htmlcontent)
控制器:
[HttpGet]
public IActionResult Index()
{
IRazorEngine razorEngine = new RazorEngine();
string templateText = "<h1>Hello @Model.Name<h1> <table>@foreach (var item in Model.Items) {<tr>@item</tr>}</table>";
IRazorEngineCompiledTemplate<RazorEngineTemplateBase<TestModel>> template = razorEngine.Compile<RazorEngineTemplateBase<TestModel>>(templateText);
var model = new RazorModel();
model.htmlcontent = template.Run(instance =>
{
instance.Model = new TestModel()
{
Name = "Rena",
Items = new[] { 3, 1, 2 }
};
});
return View(model);
}
如果您使用 asp.net core 3.x 或任何其他版本,您可以安装RazorEngine.NetCore库并按照文档操作:
[HttpGet]
public IActionResult Index()
{
var model = new RazorModel();
string template = "<h1>Hello @Model.Name<h1> <table>@foreach (var item in Model.Items) {<tr>@item</tr>}</table>";
model.htmlcontent =
Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" , Items = new[] { 3, 1, 2 } });
return View(model);
}
推荐阅读
- pytorch - Pytorch - 移植@运算符
- python - 熊猫多索引列样式器
- javascript - 没有让我的 Javascript 在 elementor wordpress 中工作
- javascript - 如何 PHP 服务器端渲染 (SSR) 生成 100% javascript 的 URL,然后将其保存到静态 html 文件
- mysql - 删除重复记录的存储程序
- html - 在 mat-tree-node 中禁用 mat 图标
- java - 通过命令行调用时 SpringTools Suite 中缺少 tools.jar
- excel - 使用 VBA 将版本信息添加到 Excel 文件属性,使用 PowerShell 读取
- java - 为通常返回 void 的函数返回字符串是否被认为是不好的做法?
- c - 将微服务(使用 ZeroMQ、C 和 Python 进程)从 64 位硬件移动到 32 位硬件后的延迟,但名义上的 cpu 使用率