[英]Escaping double quotes for JS within Razor
我正在使用GoJS库绘制图形。 我正在尝试在页面上显示以下JavaScript代码(这是完成加载后需要作为页面源的内容):
myDiagram.model = new go.GraphLinksModel([
{ key: "Node26", color: "lightgreen"},
{ key: "Node25", color: "lightgreen"},
{ key: "Node33", color: "lightgreen"},
{ key: "Node42", color: "lightgreen"}],
[
{ from: "Node26, to: "Node25"},
{ from: "Node26, to: "Node33"},
{ from: "Node33, to: "Node42"},
{ from: "Node33, to: "Node41"},
{ from: "Node33, to: "Node57"},
{ from: "Node33, to: "Node25"},
{ from: "Node33, to: "Node34"}
]);
此代码在服务器上使用如下剃刀语法生成:
@{
string nodes = "";
string links = "";
string childName;
foreach (Node node in Model.FullGraph)
{
nodes += "{ key: \"" + node.NodeName + "\"},";
@foreach (uint childId in node.ChildrenIds)
{
childName = Model.FullGraph.Find(x => x.NodeId == childId).NodeName;
links += "{ from: \"" + node.NodeName + "\", to: \"" + childName + "\"},";
}
}
}
myDiagram.model = new go.GraphLinksModel([@nodes], [@links]);
但是,加载后,结果页面在HTML中如下所示:
myDiagram.model = new go.GraphLinksModel([
{ key: "Node26", color: "lightgreen"},
{ key: "Node25", color: "lightgreen"},
{ key: "Node33", color: "lightgreen"},
{ key: "Node42", color: "lightgreen"}],
[
{ from: "Node26, to: "Node25"},
{ from: "Node26, to: "Node33"},
{ from: "Node33, to: "Node42"},
{ from: "Node33, to: "Node41"},
{ from: "Node33, to: "Node57"},
{ from: "Node33, to: "Node25"},
{ from: "Node33, to: "Node34"}
]);
使用反斜杠转义不起作用,代码仍将双引号替换为“,因此不会绘制图形。当我使用浏览器中的开发人员工具将其手动替换为普通双引号时,将绘制图形。
我也尝试过使用@
进行转义,以及使用Html.Raw()
。 什么都没有。 有人有建议吗? 预先感谢您的帮助!
出于好奇,我同时也尝试了不同的选择,让我分享一下我测试过的迭代。
我建立了一个小类进行测试:
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"
}
};
Apostrophe版本:然后在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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.