我正在尝试将以下razor语法重新编码为可行的代码并且卡住了:
var ServiceIndex = @ViewBag.ServiceID ;
var ServiceName = @ViewBag.ServiceName ;
var ServiceNotes = @ViewBag.ServiceNotes ;
我的问题是,现在这三个数组的ViewBag是空的,所以它就是单独的分号。
答案 0 :(得分:5)
您需要在服务器端将其转换为JSON。
<script>
var ServiceNotes = @(Html.Raw(JsonConvert.SerializeObject(ViewBag.ServiceNotes)));
var ServiceName = @(Html.Raw(JsonConvert.SerializeObject(ViewBag.ServiceName)));
var ServiceIndex = @(Html.Raw(JsonConvert.SerializeObject(ViewBag.ServiceIndex)));
</script>
然后直接在JS中访问它。
空数组由JsonConvert正确处理,所以,如果它是空的,你会得到像
这样的东西var ServiceNotes = [];
为了便于调试和避免嵌套函数调用,您还可以拆分序列化和输出。
@{
string serviceNotesJson = JsonConvert.SerializeObject(ViewBag.ServiceNotes);
string serviceNameJson = JsonConvert.SerializeObject(ViewBag.ServiceName);
string serviceIndexJson = JsonConvert.SerializeObject(ViewBag.ServiceIndex);
}
@section scripts
{
<script>
var ServiceNotes = @(Html.Raw(serviceNotesJson));
var ServiceName = @(Html.Raw(serviceNameJson));
var ServiceIndex = @(Html.Raw(serviceIndexJson));
</script>
}