2

我只见树木不见森林。

为什么这会引发字符串格式异常?

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

2 回答 2

10

看看你的格式字符串的这一点:

function () { ... }

这些大括号被解释为占位符的开始/结束。您需要将它们加倍:

function () {{ ... }}

因此,您的完整声明将是:

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>";
于 2013-08-19T16:46:20.193 回答
4

您必须将大括号更改{{{

于 2013-08-19T16:46:43.077 回答