Peej
Peej

Reputation: 13

How to display Cshtml from Model property? ASP NET Core MVC

I think my problem is somewhat simple hopefully. Using ASP.NET Core MVC and Visual Studio.

I have a database that will store cshtml. I will be reading this into the model property at the top of the index.cshtml file.

For certain sections, I need to display this cshtml as it would render, if I just had it in the cshtml file to begin with.

Using this works, MOSTLY --> @Html.Raw(Model.htmlcontent)

However, all of the @Model.Property bits are showing up like that, instead of actually inserting the value like I want.

Is there another method like Html.Raw that can do this, or a good approach for this?

Thank you

Upvotes: 1

Views: 2691

Answers (1)

Rena
Rena

Reputation: 36655

You stored the razor view in database, so you need firstly compile the razor code to actual html code then use @Html.Raw() to display the html code with style.

If you just want to display the model property, you can use RazorEngineCore library which only supports .net 5:

Model:

public class RazorModel
{
    public string htmlcontent { get; set; }
}
public class TestModel
{
    public string Name { get; set; }
    public int[] Items { get; set; }
}

View:

@model RazorModel

@Html.Raw(Model.htmlcontent)

Controller:

[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);
}

If you use asp.net core 3.x or any other version, you can install RazorEngine.NetCore library and follow the document:

[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);
}

Upvotes: 1

Related Questions