首页 > 解决方案 > 如何从模型属性显示 Cshtml?ASP.NET 核心 MVC

问题描述

我认为我的问题希望有点简单。使用 ASP.NET Core MVC 和 Visual Studio。

我有一个将存储 cshtml 的数据库。我将把它读入index.cshtml文件顶部的模型属性中。

对于某些部分,如果我只是将它放在 cshtml 文件中,我需要显示它会呈现的样子。

使用这个工程,大部分 -->@Html.Raw(Model.htmlcontent)

但是,所有@Model.Property位都像这样显示,而不是像我想要的那样实际插入值。

有没有像 Html.Raw 这样的另一种方法可以做到这一点,或者是一个好的方法?

谢谢

标签: c#razorasp.net-core-mvc

解决方案


您将剃刀视图存储在数据库中,因此您需要首先将剃刀代码编译为实际的 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);
}

推荐阅读