我正在使用Spark视图引擎开发一个网站。其中一个spark视图定义了viewdata,用于在相同的spark视图中定义的javascript中,并且看起来像这样:(简称):
<viewdata model="ConversationViewModel"/>
<content name="Conversation">
...
<script type="text/javascript">
$(function () {
conversation.init("$!{Model.RelationFullName}");
});
</script>
</content>
这里的问题是RelationFullName属性可以包含单引号和/或双引号的值。
有没有办法逃避报价?
答案 0 :(得分:1)
您可以创建一个以JavaScriptEscape
作为其第一个参数的扩展方法this string
,然后在_global.spark中添加一个use标记。该方法将替换任何special characters并返回结果。只需确保首先替换反斜杠,否则'
将变为\\'
而不是\'
。
namespace Whatever.Your.Namespace.Is
{
public static class MyStringExtensions
{
public static String JavaScriptEscape(this String p_string)
{
p_string = p_string ?? String.Empty;
p_string = p_string.replace("\\", "\\\\");
/* Do the rest of the replacements, include single and double quotes. */
return p_string;
}
}
}
在_global.spark中:
<use namespace="Whatever.Your.Namespace.Is" />
您的JavaScript系列将是:
conversation.init("$!{Model.RelationFullName.JavaScriptEscape()}");
祝你好运!