user424134
user424134

Reputation: 532

Why is there a FormatException with string using braces ({ })?

I am trying to create a simple JavaScript file to inject from code behind and want to append variables names to message.

 string javascript = string.Format
                            (
                                @"var msg = '{0} ';
                                 if(confirm(msg))
                                {                                          
                                    hdnfield.value='Yes';
                                } else {
                                    hdnfield.value='No';
                                }
                                    submit();", variableName);

but getting an FormatException. What is the right way to do this?

Thanks as always.

Upvotes: 0

Views: 153

Answers (2)

Chris Disley
Chris Disley

Reputation: 1345

I take it you mean you're feeding the entire file into a String.Format(format, value1, value2, value3...) in ASP.NET.

If so, you're going to have problems doing that with Javascript as it's going to interpret every opening and closing curly brace as a start or end of a token to replace.

You'd probably do better to use some sort of placeholder in the template like ##MYTOKEN## or $$SOMEVALUE$$, load that file into a string and use some String.Replace(whatToReplace, whattoReplaceItWith) functions to do the replacements.

Means you can define your own rules on what to replace with what.
String.Format is incredibly flexible and powerful, but not with unescaped curly braces in the content.

Upvotes: 0

Brandon
Brandon

Reputation: 69953

Your braces in the if/else statement are not escaped, that is causing problems with the call to string.Format which uses braces to indicate the placeholders.

string javascript = string.Format
    (
        @"var msg = '{0} ';
         if(confirm(msg))
        {{                                          
            hdnfield.value='Yes';
        }} else {{
            hdnfield.value='No';
        }}
            submit();", variableName);

Upvotes: 4

Related Questions