Rendering HTML Content With @Html.Raw in Razor Mail Template

Rendering HTML content with @Html.Raw in Razor Mail Template

When doing e-mails, I use the RazorEngineService in RazorEngine.Templating, e.g. in my case, it looks like this:

using RazorEngine.Templating;

RazorEngineService.Create().RunCompile(html, ...)

Assuming you are using the same assembly, @Html.Raw does NOT exist with this usage. I was finally able to get raw HTML output by doing this in my e-mails:

@using RazorEngine.Text

@(new RawString(Model.Variable))

Razor tag inside Html.Raw(...)

You may have some architectural issues that lead you to have some razor code on your Model property.

Anyway, you can do it by using some external libs such RazorTemplates.

Here is a sample :

var template = Template.Compile(Model.myRawHtmlContainingRazorTags);

Inserting html using the RazorEngine to be rendered as HTML is populated template

Model.URL isn't a string. It's probably a Newtonsoft.Json.Linq.JValue. You'll need to convert it to a string first using:


Just be careful and ensure Model.URL isn't null.

Generate html in body with RazorEngine email template


The solution has been found here:

And here: RazorEngine: cannot use Html.Raw

It's enough to use @(new RawString("html string here")) or @Raw("html
string here") instead of @Html.Raw("html string here").

Render Html code with razor

You should use:


Decode and then render in html

How do I output raw html when using RazorEngine (NOT from MVC)

RazorEngine, like MVC's Razor View Engine, will automatically encode values written to the template. To get around this, we've introduce an interface called IEncodedString, with the default implementations being HtmlEncodedString and RawString.

To use the latter, simply make a call to the inbuilt Raw method of TemplateBase:


Store a path with tilde (~) and display it with html.raw in razor

You can use the Url.Content method like this:

var markup = $@"<img src=""{Url.Content("~/images/image.png")}"">";

Or, if you prefer to use string.Format instead of $:

var markup = string.Format(@"<img src=""{0}"">", Url.Content("~/images/image.png"));

That will turn "~/images/image.png" into an application absolute path so the actual output will be something like

<img src="/images/image.png">

Related Topics

Leave a reply