I am trying to find a solution to output a razor view from a string at runtime. I have a database that has the HTML content of the view saved. This content is then loaded through a ViewComponent and rendered out on the fly. This code is working perfectly for standard HTML scenarios using
return new HtmlContentViewComponentResult(new HtmlString("<p>A simple bit of html</p>"));
as the return type. However, the moment I try to add some dynamic content it simply treats it as RAW HTML and does not process any of the bindings
return new HtmlContentViewComponentResult(new HtmlString("<p>Name: @Model.Name</p>"));
The above code simply ignores the @ symbol and outputs the result as plain text.
Is there a way to achieve this in a simple manner?
I have some thoughts on creating and compiling the views at runtime and then assigning them a virtual path but that seems overly complicated and perhaps not the right approach (not to mention I have no idea how to achieve that).
Just for clarity, this is for a CMS type system that would allow the client to add/edit these views at runtime, hence the loading from the database approach.
EDIT : Adding some code for context. This is the InvokeAsync method in my ViewComponent. The configuration is loaded from the database. If there it a view path specified is will use that and render correctly. If there is Razor template content configured it attempts to render that but simply does so as RAW html without any model binding etc
public async Task<IViewComponentResult> InvokeAsync(int Id)
{
//Load up the component + configurations from database
var component = await _componentProvider.GetComponentByIdAsync(Id);
if (component != null && component.Configurations.Any())
{
//If the component has a view path configured use that first
string viewPath = component.GetConfiguration<string>(VIEW_PATH);
if (viewPath != null)
{
//this works and is rendered correctly using my DatabaseViewFileProvider implementation
return View(viewPath);
}
//There is no view path configured, but rather just a Razor Template/ HTML configured directly
string content = component.GetConfiguration<string>(VIEW_RAW);
//return the partial using the retrieved content. This just returns RAW html without parsing it as a Razor template i.e @Model.SomeValue etc
return new HtmlContentViewComponentResult(new HtmlString(content));
}
return Content(string.Empty);
}