2

I'm developing a website using the Spark view engine. One of the spark views has viewdata defined that is used in javascript defined in that same spark view and looks (in short) like this:

<viewdata model="ConversationViewModel"/>

<content name="Conversation">
  ...
  <script type="text/javascript">
    $(function () {
      conversation.init("$!{Model.RelationFullName}");
    });
  </script>
</content>

The problem here is that the RelationFullName property can have a value that contains single quotes and/or double quotes.

Is there a way to escape the quotes?

1 Answer 1

1

You could create an extension method JavaScriptEscape taking this string as its first parameter, then add a use tag in your _global.spark. The method would replace any special characters and return the result. Just make sure that you replace backslash first, otherwise ' will turn into \\' instead of \'.

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;
        }
    }
}

In _global.spark:

<use namespace="Whatever.Your.Namespace.Is" />

Your line of JavaScript would then be:

conversation.init("$!{Model.RelationFullName.JavaScriptEscape()}");

Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.