简体   繁体   English

在Razor中初始化JavaScript数组

[英]Initializing a JavaScript array in Razor

I have an ASP.NET MVC app that uses Razor in the views. 我有一个在视图中使用Razor的ASP.NET MVC应用程序。 I'm building a JavaScript array in my controller. 我在控制器中构建一个JavaScript数组。 Sometimes though, it will not exist. 但是有时它不存在。 For that reason, I want to initialize it on the client-side. 因此,我想在客户端初始化它。 In an attempt to do that, I have the following: 为了做到这一点,我有以下几点:

var list = '@(ViewBag.List == null ? [] : ViewBag.List)';

Unfortunately, that generates an error. 不幸的是,这会产生一个错误。 The error is: 错误是:

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS1525: Invalid expression term '['

Is there a way for me to use the ternary operator with arrays in razor? 有没有办法在剃刀中对数组使用三元运算符? If so, how? 如果是这样,怎么办?

Because Javascript operates using JSON, you should JSON serialize your list: 由于Javascript使用JSON进行操作,因此您应该JSON序列化列表:

@using Newtonsoft.Json

var list = @Html.Raw(JsonConvert.SerializeObject(ViewBag.List));
list = list || [];

In general, @Html.Raw(JsonConvert.SerializeObject(obj)) is the proper way to inject a C# object obj into a view as JSON. 通常, @Html.Raw(JsonConvert.SerializeObject(obj))是将C#对象obj作为JSON注入视图的正确方法。 IHtmlString Html.Raw(string) simply returns the string it is passed and renders it without any HTML escaping, which is what you want when you are rendering an object as JSON into a block of Javascript code. IHtmlString Html.Raw(string)仅返回传递的string ,并呈现它而无需任何HTML转义,这是将对象作为JSON呈现到Javascript代码块中时想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM