如何遍历类型化的 Viewbag 列表?

How to loop through a typed Viewbag list?

我已经通过 Viewbag 将 List<AdminUsers> 传递给 view.The 列表,然后分配给 javascript var 并循环。

但是在视图调试期间,这个 for 循环永远不会循环,尽管我已经在它上面设置了一个断点。

循环的目的是检查 adminUserList 中的任何用户是否与当前登录的用户匹配。 currentUser 也是 init,因此排除了此值为 null 的可能性。

为了调试这个原因。我测试了 Viewbag.AdminUserList 已分配并在控制器中初始化。我还在这个列表的视图中设置了一个警报,它是 init.

问题:

有谁知道为什么 javascript 中没有调用下面的 for loop

这是调试期间 js adminUserList 的值:

var adminUserList = [{"AdminID":1,"AdminDisplayName":"brianb","AdminEmailAddress":"brian@test.com"},{"AdminID":2,"AdminDisplayName":"wendy","AdminEmailAddress":"wendy@test.com"}];

代码:

Javascript for 循环 -

<script>

    var currentUser = '@ViewBag.CurrUser';
    var adminUserList = @Html.Raw(Json.Encode(ViewBag.AdminUserList));

    $(document).ready(function () {

        var historyTable = $('#table').DataTable({
            "order": [[6, "desc"]]
        });

        //Loop through each of the admin users, if any of
        //the admin users match the current user, hide the delete column.   
        for (var i = 0; i < adminUserList.Count; i++)
        {
            if (currentUser == adminUserList.AdminDisplayName[i]) {
                //hide the delete table option from a non admin user
                historyTable.columns([9]).visible(false);
            }

        }    

    });


</script>

控制器索引方法 -

    public ActionResult Index()
    {
            HistoryDAL sqlConnection = new HistoryDAL();
            List<AdminUsers> adminList = sqlConnection.GetAdminUsers();

            //Get the current user
            var components = User.Identity.Name.Split('\');
            var userName = components.Last();

            //Assign current user and admin list to viewbag
            ViewBag.CurrUser = userName;
            ViewBag.AdminUserList = adminList;

            return View("Index");

    }

型号 - AdminUsers:

public class AdminUsers
{
    public int AdminID { get; set; }
    public string AdminDisplayName { get; set; }
    public string AdminEmailAddress { get; set; }

}

在行

for (var i = 0; i < adminUserList.Count; i++)

您需要使用 JavaScript adminUserList.length 而不是 C# adminUserList.Count,因为 adminUserList 是一个 JavaScript 变量而不是 C# 变量。