简体   繁体   中英

How do I include HTML in an onclick event inserted with Razor?

I would like to insert an onclick event with Razor that opens a new window and writes html to it that is contained in a Model property.

Here is some code that works with a simple Hello World string:

for (var i = 0; i < Model.EmailDetails.Length; i++)
{
  var emailClick = "var wnd=window.open('about:blank','','_blank'); wnd.document.write('Hello World');";
  <small>
  <i class="fa fa-envelope" onclick="@emailClick" ></i>
  Some other text
  </small>
}

But if I try to insert some HTML instead:

<p class="h4">Hello World</p>

which renders as:

onclick="var wnd=window.open('about:blank','','_blank'); wnd.document.write('<p class="h4">Hello World</p>');"

or

<p class='h4'>Hello World</p>

which renders as:

onclick="var wnd=window.open('about:blank','','_blank'); wnd.document.write('<p class='h4'>Hello World</p>');"

neither is which can be work for obvious reasons.

Assuming I want to keep the html in a Model property, how can I get this to work... or is there another approach that will do it?

The problem is very simple: you should escape the attribute quotes mark for HTML markup because the JS code containing HTML markup is assigned inside C# code.

If you're using single quotes, the JS syntax error will occur because of unescaped single quote in HTML markup and you need to use double escape ( \\\\' ):

Uncaught SyntaxError: missing ) after argument list

But if you're using double quotes, it will break C# string assignment statement because the string broken in 2 parts before and after h4 (semicolon expected).

The correct usage should be like these:

1) Using escape sequence

// single quote
var emailClick = "var wnd=window.open('about:blank','','_blank'); wnd.document.write('<p class=\\'h4\\'>Hello World</p>');";

// double quotes
var emailClick = "var wnd=window.open('about:blank','','_blank'); wnd.document.write('<p class=\"h4\">Hello World</p>');";

2) Using literal/verbatim string

var emailClick = @"var wnd=window.open('about:blank','','_blank'); wnd.document.write('<p class=""h4"">Hello World</p>');";

Update:

Since the HTML string passed from string property and single quote used for document.write in JS code, just use string.Replace() to escape the quotes with \\\\' or \\" , hence creating valid JS statement:

// single quote escape
var emailClick = "var wnd=window.open('about:blank','','_blank'); wnd.document.write('" + Model.EmailHtml.Replace("'", "\\'") + "');";

// double quote escape
var emailClick = "var wnd=window.open('about:blank','','_blank'); wnd.document.write('" + Model.EmailHtml.Replace("'", "\"") + "');";

Working example: .NET Fiddle

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