Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RazorEngine.Text.RawString not working on regular MVC partial view

I reuse the same partial for a RazorEngine email using RazorEngine.Parse, but when I use the same Partial in a regular view new RazorEngine.Text.RawString doesnt work and doesnt ignore HTML. I cant use Html.Raw because the RazorEngine cant read it. How can I get around this?

<p>
    @(new RazorEngine.Text.RawString(Model.Body))
</p>

Shows the bottom markup in a regular asp.net mvc razor view.

<p>
   Welcome!&lt;br/&gt;&lt;br/&gt;Body
</p>
like image 697
Mike Flynn Avatar asked Sep 20 '18 21:09

Mike Flynn


1 Answers

You can specify ITemplateServiceConfiguration when creating an instance of RazorEngineService as shown in project's git repository.

Code from the Repository:

/// <summary>
/// A simple helper demonstrating the @Html.Raw
/// </summary>
public class MyHtmlHelper
{
    /// <summary>
    /// A simple helper demonstrating the @Html.Raw
    /// </summary>
    public IEncodedString Raw(string rawString)
    {
        return new RawString(rawString);
    }
}

/// <summary>
/// A simple helper demonstrating the @Html.Raw
/// </summary>
public abstract class MyClassImplementingTemplateBase<T> : TemplateBase<T>
{
    /// <summary>
    /// A simple helper demonstrating the @Html.Raw
    /// </summary>
    public MyClassImplementingTemplateBase()
    {
        Html = new MyHtmlHelper();
    }

    /// <summary>
    /// A simple helper demonstrating the @Html.Raw
    /// </summary>
    public MyHtmlHelper Html { get; set; }
}

Usage:

class Program
{
    static void Main(string[] args)
    {

        var config = new TemplateServiceConfiguration();
        config.BaseTemplateType = typeof(MyClassImplementingTemplateBase<>);
        using (var service = RazorEngineService.Create(config))
        {
            string template = "<p>@Html.Raw(Model.Body)</p>";
            var result = service.RunCompile(template, "templateKey", null, new { Body = "Welcome!<br /><br /><Label>Hello</label>" });
            Console.WriteLine(result);
        }
        Console.ReadLine();
    }
}

Only thing you need to remember is to provide ITemplateServiceConfiguration object when creating an instance of RazorEngineService.

P.S: @(new RazorEngine.Text.RawString(Model.Body)) is not working in partial view because it is wrapped around @() and any string from the directive will be encoded before it is written to the output stream.

like image 110
Dipen Shah Avatar answered Oct 16 '22 03:10

Dipen Shah