1

Model.Choices is a string array in my MVC3 view. My question is, how can I get a JavaScript string array from it? If you do something like:

var choices="@Model.Choices";
alert(choices);
alert(choices[1]);

The message will be "choice1choice2choice3choice4" and "undefined"

What is the syntax I need to have to have choices turn into a string array in JavaScript? For example:

alert(choices[0]);
alert(choices[1]);

Should output "choice1", and "choice2".

2 Answers 2

4
var choices = [ '@Html.Raw(string.Join("', '", Model.Choices))' ];

Please note, if you have 0 items, this will fail by adding one empty item to the array. You should ensure that the choices won't have any ' (single quotes).

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

1 Comment

Doing this didn't work. I got choice1', 'choice2', 'choice3', 'choice4 when I alerted choice[0] but undefined if I tried choice[1]
0
['@string.Join("','", Model.Choices)']

2 Comments

Doing this didn't work. I got choice1', 'choice2', 'choice3', 'choice4 when I alerted choice[0] but undefined if I tried choice[1]
output un-escaped html (@Html.Raw)

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.