0

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?

4
  • [] isn't valid C# code. What type is ViewBag.List? Do you want to serialize something into JavaScript? Commented Oct 10, 2014 at 15:38
  • Try var list = '@(ViewBag.List == null ? "[]" : ViewBag.List)'; Commented Oct 10, 2014 at 15:38
  • @elolos That approach generates var list = '[]'; not var list = []; Commented Oct 10, 2014 at 15:51
  • Sorry, meant var list = @(ViewBag.List == null ? "[]" : ViewBag.List); Commented Oct 10, 2014 at 15:56

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I thought I've read pickles somewhere here. Now it disappeared.
I think when you posted the first version of the answer there was a Model with pickles in its name. Nevermind. :)
@MelanciaUK Ahaha yes I copied a snippet out of a view of my own and forgot to switch out for ViewBag.List but then immediately corrected it. It wasn't "pickles" though.
I might be hungry. That's why. Haha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.