syncis
syncis

Reputation: 1433

Loop list in jquery

I have a list :

public List<Sale> AllSales { get; set; }

And i would like to loop it in jquery :

 $(document).ready(function() {

            for (var i = 0; i < <%= AllSales %>; i++) {
                 alert("test");
            }

         });

But i am not getting any alerts or anything, what am i doing wrong?

Upvotes: 2

Views: 73

Answers (4)

Felipe Oriani
Felipe Oriani

Reputation: 38608

Considering your type View

@model List<Sale>

Try this:

for (var i = 0; i < <%= Model.Count %>; i++) {
    // operations...
}

If it is a property of your model, so, try this:

for (var i = 0; i < <%= Model.AllSales.Count %>; i++) {
   // operations...
}

I also recoment you change from List<Sale> to IEnumerable<Sale> and use Count() from method to get the lenght of the list from System.Linq . IEnumerable is more abstract than List and you will be protected to add items on the List on View scope.

Upvotes: 0

WEFX
WEFX

Reputation: 8552

You can use jquery to get the count of dropdown objects:

var myCount = $('#myDropDown > option');

... and then use this new variable in your loop definition.

Upvotes: 0

Adil
Adil

Reputation: 148120

Use AllSales.Count instead of AllSales to limit the loop. If you want to access values of the list then you may need to use ajax to bring the values to javascript.

$(document).ready(function() {

     for (var i = 0; i < <%= AllSales.Count %>; i++) {
             alert("test");
     }
});

Upvotes: 2

Blachshma
Blachshma

Reputation: 17385

You need to use Count property, e.g.

$(document).ready(function() {

        for (var i = 0; i < <%= AllSales.Count %>; i++) {
             alert("test");
        }

});

Upvotes: 4

Related Questions