我正在使用 Spark View 引擎开发一个网站。其中一个 spark View 定义了 viewdata,它在同一 spark View 中定义的 javascript 中使用,看起来(简而言之)如下所示:
<viewdata model="ConversationViewModel"/>
<content name="Conversation">
...
<script type="text/javascript">
$(function () {
conversation.init("$!{Model.RelationFullName}");
});
</script>
</content>
这里的问题是 RelationFullName 属性的值可以包含单引号和/或双引号。
有没有办法转义引号?
最佳答案
您可以创建一个扩展方法 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()}");
祝你好运!
关于javascript - 使用 Spark View 引擎的 View 数据调用参数包含引号的 javascript 函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11775875/