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

前端 未结 3 1619
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 22:54

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:



        
相关标签:
3条回答
  • 2020-11-27 23:36

    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;
      ....
    });
    
    0 讨论(0)
  • 2020-11-27 23:38
    <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>
    
    0 讨论(0)
  • 2020-11-27 23:40

    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?

    0 讨论(0)
提交回复
热议问题