Search code examples
javascriptc#stringbuilder

Stringbuilder.ToString() Converting " and ' symbol generate ' and " in javascript


I wrote some dynamic javascript code into StringBuilder, but when I am converting StringBuilder object to string it converting symbols into html code. below is my code:

System.Text.StringBuilder gastring = new System.Text.StringBuilder();
  @foreach (var line in OrderLines)
 {
     gastring.AppendLine("ga('ecommerce:addItem', {");
                gastring.AppendLine("id:\"" + line.OrderNumber + "\",       // Order ID");
                gastring.AppendLine("sku:\"" + line.SkuCode + "\",                                     // SKU");
                gastring.AppendLine("name:" + Microsoft.Security.Application.AntiXss.JavaScriptEncode(line.SkuName) + ",                                  // Product Name ");
                gastring.AppendLine("category:\"" + " " + "\",                                    // Category");
                gastring.AppendLine("price:\"" + line.UnitPrice + "\",                                    // Price");
                gastring.AppendLine("quantity:\"" + line.Qty + "\"                                         // Quantity");
                gastring.AppendLine("});");
}

<script type="text/javascript">
 gastring.ToString()
 ga('ecommerce:send');
</script>

But when I am running this code, gastring.ToString() line generating javascript code as below:

ga(&#39;ecommerce:addItem&#39;, {
id:&quot;HGT678&quot;,       // Order ID
sku:&quot;HI789&quot;,                                     // SKU
name:&#39;Test Item 456&#39;,                                  // Product Name 
category:&quot; &quot;,                                    // Category
price:&quot;337.0000&quot;,                                    // Price
quantity:&quot;1&quot;                                         // Quantity
});

expected Output should be as below:

ga('ecommerce:addItem', {
id:"HGT678",       // Order ID
sku:"HI789",                                     // SKU
name:"Test Item 456",                                  // Product Name 
category:" ",                                    // Category
price:"337.0000",                                    // Price
quantity:"1"                                         // Quantity
});

Need help on this issue.

Thanks,
Sandy


Solution

  • If you are in ASP.NET MVC, strings are escaped by default, try Html.Raw

    @Html.Raw(gastring.ToString())