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:
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;
....
});
<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>
JavaScript generally is unhappy with razor components although if the above is part of an CSHTML file it will work.
The other approaches are:
@foreach ...
How are you calling this function and what does it do?