0

I have a collection that I would like to iterate over, which is held in a C# variable.

I would like to iterate over this using a for loop from within Javascript; is this possible?

For example:

@{ int questionCount = 0;
foreach(var q in Model.Questions){ 
questionCount++;
}

...do some HTML...

<script type="text/javascript">
jQuery(function () {


for (var i=1;i<=@questionCount;i++)
{        

    var d1 = @Model.Questions[i].Answers.Where(m => m.Answer == 1).Count(); 
    <-- this is where it breaks -->
}

});

The error I get says that the index is out of range. I guess this means that it doesn't understand 'i' once I've put the @ symbol into the line. How can I delimit the string correctly to use the variable i (from Javascript) to iterate over my C# collection?

2 Answers 2

1

This does not work. You cannot access client-side variables in a server-side code block.

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

9 Comments

As I thought, thanks for the confirmation. Since I can ask for something like var d1 = @Model.Questions[0].Answers.Where(m => m.Answer == 1).Count(); (i.e. set the index to zero), and since I know the value of that index (from within the loop), is there a way to construct this single line dynamically?
You can create some code to run on the server that generates JavaScript (i.e., code that will then run on the client) in a string, then you output that string in your .CSHTML.
That sounds promising. I'm a bit of a newbie to this stuff, would it be C# code that generates Javascript?
Yes, C# that generates a string that contains JavaScript. You then output that string in your HTML, for instance by displaying a property @Model.GeneratedCode or whatever you wish to call it.
Looks like I spoke too soon. I'm just getting the script printing in plain text on screen. If I paste this into the .cshtml file then reload, it works. Any ideas why the javascript is just printing in plain text?
|
0

You can not use server side models in your javascript, These models are relevant only on server side for generating HTML.

If you really need a value in your javascript code then you can put the model's value in some hidden html element.

1 Comment

Thanks @Asif; can you elaborate on your second sentence? Also, Since I can ask for something like var d1 = @Model.Questions[0].Answers.Where(m => m.Answer == 1).Count(); (i.e. set the index to zero), and since I know the value of that index (from within the loop), is there a way to construct this single line dynamically?

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.