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!<br/><br/>Body
</p>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With