Render razor from database or other sources

2019-07-30 00:50发布

问题:

I would like to render the razor code from the database to to a razor view. Would thatbe possible?

CONTROLLER/ACTION:

public ActionResult About()
{
    ViewBag.Message = "Your application description page.";
    ViewBag.RazorCode = "@Html.TextBox(\"txtTestRazor\")";
    return View();
}

VIEW:

@{
    ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>Use this area to provide additional information.</p>

<h3>@ViewBag.RazorCode</h3>

HTML/OUTPUT:

About.

Your application description page.

Use this area to provide additional information.
@Html.TextBox("txtTestRazor")

回答1:

One option is to use RazorEngine

Basics are very easy, just give it a string (and a model)

string template = "Hello @Model.Name! Welcome to Razor!";
string result = Razor.Parse(template, new { Name = "World" });

It doesn't support html helpers, routing etc. out of the box (as far as I remember).