【发布时间】:2018-01-03 13:59:29
【问题描述】:
我的网络应用程序出现问题,我正在从数据库中检索数据,然后将其通过 ViewBag 传递给 View,最后将数据转换为 javascript 对象。
这是一个带有虚拟数据的示例
控制器
public ActionResult Index()
{
var boxer = new
{
Name = "Juan Manuel Márquez",
Division = "Welterweight"
};
ViewBag.Data = new
{
Boxer = boxer
};
return View();
}
查看
<div>
Hello there!
</div>
@section scripts {
<script>
$(document).ready(function() {
var myModel = JSON.parse('@Html.Raw(Json.Encode(ViewBag.Data))');
console.log(myModel);
});
</script>
}
结果如预期:一个具有模型属性的对象。但问题是当拳击手的名字中包含他的别名时,例如:
var boxer = new
{
Name = "Juan Manuel \"Dinamita\" Márquez",
Division = "Welterweight"
};
这会导致下一个错误,因为 JSON.Encode 生成一个 JSON 字符串而不转义引号
VM38:1 Uncaught SyntaxError: 位置 31 处 JSON 中的意外标记 D 在 JSON.parse() 在 HTML 文档。 (索引:53) 着火(jquery-1.10.2.js:3062) 在 Object.fireWith [as resolveWith] (jquery-1.10.2.js:3174) 在 Function.ready (jquery-1.10.2.js:447) 在 HTMLDocument.completed (jquery-1.10.2.js:118)
有什么建议吗?
问候
【问题讨论】:
标签: json asp.net-mvc asp.net-mvc-5 double-quotes viewbag