model.DepartmentsList = list;
model.DepartmentsListJson = JsonConvert.SerializeObject(model.DepartmentsList);
返回此JSON
:
“ [{{\” DeptNo \“:\” d006 \“,\” DeptName \“:\” Production \“,\” FromDate \“:null,\” ToDate \“:null},{\” DeptNo \“:\” d007 \“,\” DeptName \“:\” Sales \“,\” FromDate \“:null,\” ToDate \“:null},{\” DeptNo \“:\\ d009 \ “,\” DeptName \“:\”客户 服务\“,\” FromDate \“:空,\” ToDate \“:空},{\” DeptNo \“:\\” d021 \“,\” DeptName \“:\” DEV \“,\” FromDate \ “:null,\” ToDate \“:null},{\” DeptNo \“:\” d022 \“,\” DeptName \“:\” Human 资源资源 5 \“,\” FromDate \“:null,\” ToDate \“:null},{\” DeptNo \“:\\” d023 \“,\” DeptName \“:\” Human 资源资源 6 \“,\” FromDate \“:null,\” ToDate \“:null},{\” DeptNo \“:\\” d024 \“,\” DeptName \“:\\” Human 资源7 \“,\” FromDate \“:null,\” ToDate \“:null}]”
(忽略空值)。当我尝试用javascript解析它时
var departmentsList = JSON.parse(@Model.DepartmentsListJson);
我收到以下消息:
Uncaught SyntaxError: Unexpected token &
我应该使用什么来从我的JSON
代码中返回有效的C#
字符串?
答案 0 :(得分:4)
您尝试过吗:
var departmentsList = JSON.parse(@Html.Raw(@Model.DepartmentsListJson));
问题是您将c#与razor和javaScript混合。因此,当您这样做时:
var departmentsList = JSON.parse(@Model.DepartmentsListJson);
除非我误解了您在c#中访问对象,而不是它包含的实际值。