Jon
Jon

Reputation: 40032

Why is this throwing a string format exception

I can't see the wood for the trees.

Why is this throwing a String Format Exception?

 private const string GoogleAnalyticsFormat = @"<script type=""text/javascript"">
                                                var _gaq = _gaq || [];

                                                _gaq.push(['_setAccount', '{0}']);
                                                _gaq.push(['_trackPageview']);

                                                (function () {
                                                    var ga = document.createElement('script');
                                                    ga.type = 'text/javascript';
                                                    ga.async = true;
                                                    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                                                    var s = document.getElementsByTagName('script')[0];
                                                    s.parentNode.insertBefore(ga, s);
                                                })();
                                            </script>";

public static IHtmlString RenderGoogleAnalytics<T>(this HtmlHelpers<T> html, string trackingCode )
{
    return html.Raw(string.Format(GoogleAnalyticsFormat, trackingCode));
}

Upvotes: 2

Views: 228

Answers (2)

Blau
Blau

Reputation: 5762

You have to change braces { to {{

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500105

Look at this bit of your format string:

function () { ... }

Those braces are being interpreted as the start/end of placeholders. You need to double them:

function () {{ ... }}

So your complete declaration would be:

private const string GoogleAnalyticsFormat = @"<script type=""text/javascript"">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', '{0}']);
    _gaq.push(['_trackPageview']);
    (function () {{
        var ga = document.createElement('script');
        ga.type = 'text/javascript';
        ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
    }})();
    </script>";

Upvotes: 10

Related Questions