简体   繁体   中英

Initializing a JavaScript array in Razor

I have an ASP.NET MVC app that uses Razor in the views. I'm building a JavaScript array in my controller. 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:

@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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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