1 回答

TA貢獻1852條經驗 獲得超7個贊
出于好奇,我同時嘗試了不同的選項,讓我分享我測試過的迭代。
我建立了一個小類進行測試:
public class ColoredObject
{
public string key { get; set; }
public string color { get; set; }
}
出于測試目的,創建了一個列表,其中添加了 2 個測試對象:
var list = new List<ColoredObject>()
{
new ColoredObject()
{
key = "Node26",
color = "lightgreen"
},
new ColoredObject()
{
key = "Node25",
color = "lightgreen"
}
};
撇號版本: 然后在 Razor 中創建 JSON 對象:
string nodesWithApostrophe = "[";
foreach (var i in list)
{
nodesWithApostrophe += "{ key: '" + i.key + "', color: '" + i.color + "'},";
}
nodesWithApostrophe += "]";
因此,第一個工作正常并正確記錄到控制臺的解決方案如下所示:
let jsonObject = @Html.Raw(nodesWithApostrophe);
console.log('testJson with apostrophe', jsonObject);
雙引號版本: 我對如何用雙引號創建對象也很感興趣,所以我更改為在 foreach 中轉義字符:
string nodesWithDQ = "[";
foreach (var i in list)
{
nodesWithDQ += "{ key: \"" + i.key + "\", color: \"" + i.color + "\"},";
}
nodesWithDQ += "]";
在 JavaScript 中也做同樣的事情使其工作:
let jsonObject = @Html.Raw(nodesWithDQ);
console.log('testJson with double quotes', jsonObject);
- 1 回答
- 0 關注
- 171 瀏覽
添加回答
舉報