dealing with nested quotes in html generated from c#

廉价感情. 提交于 2019-12-24 01:58:18

问题


i am using a 3rd party library to show tooltips, like so:

string tooltip = "test";
output.Write("onmouseover='Tip(\"" + test + "\");'");  // work fine :)

i'm having problem with situations like the following where i need quotes for formatting:

string tooltip = "<span style='color:red;'>test</span>";
output.Write("onmouseover='Tip(\"" + test + "\");'");  // no working :(

how can i escape the quotes needed for the html in the tooltip so it doesn't break the function call?


回答1:


Replace any instance of " with &quot; as follows:

test.Replace( "\"", "&quot;" )



回答2:


This is the perfect use for the Microsoft Anti-Xss Library

With it, you call the JavaScriptEncode function, which will build a string like this:

Microsoft.Security.Application.AntiXss.JavaScriptEncode("ab'c\"d")
// 'ab\x27c\x22d'

Notice that it includes the quotes.

You would take that, HTML encode it, and plop it directly into your parenthesis.

Something like this:

string tooltip = "<span style='color:red;'>test</span>";
output.Write("onmouseover=\"Tip(" + AntiXss.JavaScriptEncode(test) + ");\"");  // working :)


来源:https://stackoverflow.com/questions/2223543/dealing-with-nested-quotes-in-html-generated-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!