[英]Is there automatic formatting for an asp:literal control?
Is there a way to automatically format a string
for literal insertion into JavaScript code?有没有办法自动格式化
string
以将文字插入 JavaScript 代码?
Say you have this in your page:假设您的页面中有这个:
<script type="text/javascript">
var strvar = <asp:Literal runat="server" id="ltrStrvar"></asp:Literal>;
</script>
And in your server-side code:在您的服务器端代码中:
protected void Page_Load(object sender, EventArgs e) {
ltrStrvar.Text = "hello \"world\"";
}
Is there a way to automatically have it escape the string and surround it with quotes for error-free insertion into JavaScript, so all I have to do is set the Text
property with an arbitrary string?有没有办法自动让它转义字符串并用引号将其括起来以无错误地插入到 JavaScript 中,所以我所要做的就是使用任意字符串设置
Text
属性? I know how to do it manually but was looking for a more elegant solution.我知道如何手动完成,但正在寻找更优雅的解决方案。
您可以创建一个自定义的LiteralWithQuotationMarks
用户控件,该控件在内部使用Literal
控件并在缺少引号时将其括起来。
You could do something like this:你可以这样做:
public string sanitizeJavascriptString(string dirtyInput)
{
return dirtyInput.Replace("\\", "\\\\")
.Replace("\"", "\\\"")
.Replace("'","\\'");
}
I don't know if there is an existing escape function, but I doubt it.我不知道是否有现有的转义功能,但我对此表示怀疑。 I'm also not 100% sure what else needs to be escaped, but I assume you can add the other characters if you know what they are.
我也不是 100% 确定还需要转义什么,但我假设您可以添加其他字符,如果您知道它们是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.