jQuery:如何遍历/迭代对象列表
我正在使用asp.net MVC4进行Web应用程序开发。
我想遍历ViewModel中的对象列表。
下面是对象的类:
public class User { public int Id {get; set;} public string Name {get; set;} public string Address {get; set;} public string Department {get; set;} }
下面是我的ViewModel
类:
public class UserViewModel { public List AllUsers {get; set;} public bool IsDeleted {get; set;} }
如在UserViewModel
类中所见,我有一个User
类型的对象列表。 现在我想使用Jquery
迭代AllUsers
列表中的每个用户对象并从中获取数据。
为了做到这一点,我尝试做类似以下的事情:
$(@Model.AllUsers).each( function(){ .... });
我尝试过使用上述方法的不同组合,但无法成功。 任何人都可以提出相同的解决方案。
提前致谢。
使用将您的集合分配给javascript变量
var users = @Html.Raw(Json.Encode(Model.AllUsers))
然后你可以迭代
$.each(users, function(index, item) { // access the properties of each user var id = item.Id; var name = item.Name; .... });
JavaScript通常对剃刀组件不满意,但如果上面是CSHTML文件的一部分,它将起作用。
其他方法是:
- 使用razor
@foreach ...
显示集合@foreach ...
- 将集合作为参数从您的网页传递到某个事件的JavaScript函数中
你是怎么称呼这个function的?它做了什么?