-1

I have a viewmodel with a property

public List<string> Answers { get; set; }

How do I pass the values of the list to an array variable?

Currently have this javascript code in my view, but it has error on the answers array inside the foreach loop.

The name answers does not exists in the current context.

<script type="text/javascript">
    var answers = [];
    @foreach(string answer in Model.Answers)
    {
        var ans = @answer;
        answers.push(ans);
    }
</script>
Jc Balantakbo
  • 115
  • 1
  • 8
  • 2
    Because `@foreach` is razor code (parsed on the server before its sent to the browser) and `var answers` is a javascript variable - it does not even exist at that point. Use `var answers = Html.Raw(Json.Encode(Model.Answers))` –  Aug 24 '17 at 07:27
  • this worked StephenMuecke just add the '@' before the html helper "@var answers = Html.Raw(Json.Encode(Model.Answers))" – Jc Balantakbo Aug 24 '17 at 07:37
  • you should add this as an answer. Id be happy to choose it. – Jc Balantakbo Aug 24 '17 at 07:39
  • Oops - that was a typo - I'll see if a can find a suitable dupe first. –  Aug 24 '17 at 07:40

1 Answers1

0

Use Json.net for serializing Json. Use it religiously ! Then think about the cleanest way to get the json to the client. Usually this is a separate api call. We retrofitted web api to our server-rendered application so we don't even need to worry about invoking Json.net. We just return C# objects and web api converts them. (not new technology !) You really shouldn't be doing this in a razor template.

bbsimonbb
  • 27,056
  • 15
  • 80
  • 110