简体   繁体   中英

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?

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:

@Raw(Model.URL.ToString())

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

The call to @Raw() expects an IEncodedString not a literal.

For @Raw, see here

For IEncodedString, see here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM