Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Format throws System.Format exception on HTML + javascript

I'm running string.Format on a readonly string that contains a bit of HTML + javascript but I get a System.FormatException instead.

This is my format string:

<script type="text/javascript">
    function {0}_showHideFieldWindow() {
        if ({0}.IsCustomizationWindowVisible()) {
            {0}.HideCustomizationWindow();
        } else {
            {0}.ShowCustomizationWindow();
        }
    }
</script>

All i'm doing is passing in the object name. Like this:

string.Format(javascript, "grid");
like image 462
James Couvares Avatar asked Apr 30 '09 20:04

James Couvares


1 Answers

Since you have curly braces in the string you need to escape them by doubling them up ({{ and }}) to prevent the formatter from thinking they are tokens.

Your string initialization should look something like this:

String javascript = @"<script type=""text/javascript"">
            function {0}_showHideFieldWindow() {{
            if ({0}.IsCustomizationWindowVisible()) {{
                {0}.HideCustomizationWindow();
            }} else {{
                {0}.ShowCustomizationWindow();
            }}
        }}
    </script>";
like image 120
Andrew Hare Avatar answered Sep 24 '22 23:09

Andrew Hare