DarthVader
DarthVader

Reputation: 55032

Rendering Tag Helper html from a string

We have lots of tag helpers and looking to allow other developers to try and create pages through a code editor, where they write some tag helper and upon submitting, we want to render the output. We want to create something like w3

Take the minimal example as in the asp.net docs as follows:

    public class EmailTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "a";
        }
    }

We have a code editor when the user writes:

<email>[email protected]<email>

I want to execute this tag helper and render HTML string out of it which should be:

<a>[email protected]</a>

Things can get really complex as you can imagine.

Is there a way to render Tag Helper from string that comes from MVC controller?

I tried to render partial views and view components as string. But no luck. I tried using Html.Raw() with encoding and decoding but didnt help as well.

Any ideas?

Upvotes: 4

Views: 1780

Answers (1)

jimSampica
jimSampica

Reputation: 12410

Here's a little basic example on how to accomplish this. Lets assume we already have the email tag helper in place. AspNetCore 2.2

Startup.cs

In ConfigureServices(IServiceCollection services) add this bit of code

services.Configure<RazorViewEngineOptions>(options =>
{
    options.AllowRecompilingViewsOnFileChange = true;
});

This allows the view engine to detect file changes and recompile the view. If this is not set any Environment name besides Development will not work.

HomeController.cs

private readonly IHostingEnvironment _hostingEnvironment;
private readonly string _myTemplatePath;

public HomeController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
    _myTemplatePath = Path.Combine(_hostingEnvironment.ContentRootPath, @"Views\Shared\_MyTemplate.cshtml");
}

public IActionResult Index()
{
    var myTemplateCode = System.IO.File.ReadAllText(_myTemplatePath); 

    return View(new MyTemplateViewModel
    {
        TemplateCode = myTemplateCode
    });
}

[HttpPost]
public IActionResult UpdateMyTemplate(MyTemplateViewModel viewModel)
{
    System.IO.File.WriteAllText(_myTemplatePath, viewModel.TemplateCode);

    return RedirectToAction(nameof(Index));
}

public IActionResult GetMyTemplate()
{
    return View("_MyTemplate");
}

Some simple code to read/write to _MyTemplate.cshtml file which will act as the editable bit of code.

Views/Home/Index.cshtml

<form asp-action="UpdateMyTemplate" method="post">
    <textarea asp-for="TemplateCode" rows="10"></textarea><br />
    <button type="submit">Save Changes</button>
</form>

<h2>Output</h2>
<partial name="_MyTemplate" />

Running the code

enter image description here

Upvotes: 2

Related Questions