我有一個在視圖中使用Razor的ASP.NET MVC應用程序。我在我的控制器中構建了一個JavaScript數組。有時候,它不會存在。出於這個原因,我想在客戶端初始化它。試圖做到這一點,我有以下幾點:初始化Razor中的JavaScript數組
var list = '@(ViewBag.List == null ? [] : ViewBag.List)';
不幸的是,這會產生一個錯誤。錯誤是:
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 '['
有沒有辦法讓我在剃刀中使用三元運算符數組?如果是這樣,怎麼樣?
'[]'是無效的C#代碼。什麼類型是ViewBag.List?你想要將某些東西序列化爲JavaScript嗎? – dusky 2014-10-10 15:38:14
嘗試'var list ='@(ViewBag.List == null?「[]」:ViewBag.List)';' – elolos 2014-10-10 15:38:35
@elolos該方法生成'var list ='[''';'not'var list = [ ];' – user687554 2014-10-10 15:51:43