RichardMc RichardMc - 1 year ago 92
C# Question

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

I'm having a problem rendering html in a HTML template. I am currently using the razorEngine to populate templates we then use in emails. The information I am having issues with rendering is a url. Because of a client requirement we cannot have clickable links inside of emails so instead I have to have the url as a plain string, the problem with email clients is that they will render a url string as a link regardless of if you define it as a link or not. To circumvent this I have added a couple zero space images throughout the link to break it.

This is the code populating the template:

Engine.Razor.Compile(content, "template");
Engine.Razor.Run("template", null, data)

data passed in is a JObject:

"Code": "235466",
"FirstName": "First",
"LastName": "Last",
"URL": "<p>http<img src=\"\" width=\"0\" height=\"0\">s:<img src=\"\" width=\"0\" height=\"0\">//test.<img src=\"\" width=\"0\" height=\"0\">test.<img src=\"\" width=\"0\" height=\"0\">com/account/forgotpassword/</p>"

Tags in the template match with the template typically like this:

  • @Model.FirstName

  • @Model.LastName

  • @Model.LastName

Apart from the url which i'm trying to render as html:

  • @Raw(Model.URL)

The following error gets thrown when attempting the enter the values:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'RazorEngine.Templating.TemplateBase.Raw(string)' has some invalid arguments

If I was to place the URL directly into the Raw() it works correctly:

@Raw("<p>http<img src="" width="0" height="0">s:<img src="" width="0" height="0">//test.<img src="" width="0" height="0">test.<img src="" width="0" height="0">com/account/forgotpassword/</p>")

Can anyone see what I am missing here?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download