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

2019-01-04 15:14发布

I'm using asp.net 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 ViewModel class:

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

As seen in the UserViewModel class, I have a list of objects of type User. Now i would like to iterate through each of the user object in AllUsers list using Jquery 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.

3条回答
Deceive 欺骗
2楼-- · 2019-01-04 15:31

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;
  ....
});
查看更多
Melony?
3楼-- · 2019-01-04 15:31

JavaScript generally is unhappy with razor components although if the above is part of an CSHTML file it will work.

The other approaches are:

  1. Display the collection using razor @foreach ...
  2. Pass the collection as a parameter from you webpage into a JavaScript function on some event

How are you calling this function and what does it do?

查看更多
等我变得足够好
4楼-- · 2019-01-04 15:46
<script type="text/javascript">

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

    for (var i = 0; i < UsersList.length; i++) {
        alert(UsersList[i].Id);
        alert(UsersList[i].Name);

    } 
 </script>
查看更多
登录 后发表回答