Coilz
Coilz

Reputation: 21

Trouble using viewdata of the Spark view engine to call a javascript function with parameters containing quotes

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?

Upvotes: 2

Views: 293

Answers (1)

Becca
Becca

Reputation: 1580

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!

Upvotes: 1

Related Questions