Zax Zax - 1 year ago 105
jQuery Question

jQuery: How to traverse / Iterate over a list of object

I'm using MVC4 for web app development.

I would like to traverse a list of objects from a ViewModel.

Below is the class of the object:

public class User
public int Id {get; set;}
public string Name {get; set;}
public string Address {get; set;}
public string Department {get; set;}

Below is my

public class UserViewModel
public List<User> AllUsers {get; set;}
public bool IsDeleted {get; set;}

As seen in the
class, I have a list of objects of type
. Now i would like to iterate through each of the user object in
list using
and fetch data from them.

In order to do so, I tried doing something like the following:

$(@Model.AllUsers).each( function(){ .... });

I have tried different combination using the above approach, but couldn't succeed. Can anyone suggest a solution for the same.

Thanks in advance.

Answer Source

Assign your collection to a javascript variable using

var users = @Html.Raw(Json.Encode(Model.AllUsers))

which you can then iterate over

$.each(users, function(index, item) {
  // access the properties of each user
  var id = item.Id;
  var name = item.Name;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download