-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>
4
  • 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)) Commented Aug 24, 2017 at 7:27
  • this worked StephenMuecke just add the '@' before the html helper "@var answers = Html.Raw(Json.Encode(Model.Answers))" Commented Aug 24, 2017 at 7:37
  • you should add this as an answer. Id be happy to choose it. Commented Aug 24, 2017 at 7:39
  • Oops - that was a typo - I'll see if a can find a suitable dupe first. Commented Aug 24, 2017 at 7:40

1 Answer 1

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.

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

2 Comments

OP is not asking about how to get the json to the client
Can't help myself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.