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.