为什么使用大括号 ({ }) 的字符串会出现 FormatException?
我正在尝试创建一个简单的 JavaScript 文件以从后面的代码注入,并希望将变量名称附加到消息中。
string javascript = string.Format
(
@"var msg = '{0} ';
if(confirm(msg))
{
hdnfield.value='Yes';
} else {
hdnfield.value='No';
}
submit();", variableName);
但得到一个FormatException。这样做的正确方法是什么?
一如既往地感谢。
I am trying to create a simple JavaScript file to inject from code behind and want to append variables names to message.
string javascript = string.Format
(
@"var msg = '{0} ';
if(confirm(msg))
{
hdnfield.value='Yes';
} else {
hdnfield.value='No';
}
submit();", variableName);
but getting an FormatException. What is the right way to do this?
Thanks as always.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
if/else 语句中的大括号未转义,这导致调用
string.Format
时出现问题,该调用使用大括号来指示占位符。Your braces in the if/else statement are not escaped, that is causing problems with the call to
string.Format
which uses braces to indicate the placeholders.我认为您的意思是您将整个文件输入 ASP.NET 中的
String.Format(format, value1, value2, value3...)
中。如果是这样,您将在使用 Javascript 执行此操作时遇到问题,因为它将把每个左大括号和右大括号解释为要替换的标记的开始或结束。
您可能最好在模板中使用某种占位符,例如
##MYTOKEN##
或$$SOMEVALUE$$
,将该文件加载到字符串中并使用一些String.Replace(whatToReplace,whattoReplaceItWith)
函数来进行替换。意味着您可以定义自己的规则来替换什么。
String.Format
非常灵活和强大,但内容中没有未转义的花括号。I take it you mean you're feeding the entire file into a
String.Format(format, value1, value2, value3...)
in ASP.NET.If so, you're going to have problems doing that with Javascript as it's going to interpret every opening and closing curly brace as a start or end of a token to replace.
You'd probably do better to use some sort of placeholder in the template like
##MYTOKEN##
or$$SOMEVALUE$$
, load that file into a string and use someString.Replace(whatToReplace, whattoReplaceItWith)
functions to do the replacements.Means you can define your own rules on what to replace with what.
String.Format
is incredibly flexible and powerful, but not with unescaped curly braces in the content.