我在 StringBuilder 中编写了一些动态 JavaScript 代码,但是当我将 StringBuilder 对象转换为字符串时,它会将符号转换为 html 代码。下面是我的代码:
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>
但是当我运行此代码时,gastring.ToString()
行生成如下 JavaScript 代码:
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
});
预期输出应如下:
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
});
需要有关此问题的帮助。
谢谢,
桑迪
最佳答案
如果您使用 ASP.NET MVC,默认情况下会对字符串进行转义,请尝试 Html.Raw
@Html.Raw(gastring.ToString())
关于javascript - Stringbuilder.ToString() 转换 "and ' 符号在 javascript 中生成 ' 和 ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55789688/