我已经通过Viewbag将List<AdminUsers>传递给视图,然后将该列表分配给javascript var并循环遍历。

但是,尽管在视图上进行了调试,但在视图上进行调试的for循环却从未循环过。

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

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

题:

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

这是调试期间js adminUserList的值:

var adminUserList = [{"AdminID":1,"AdminDisplayName":"brianb","AdminEmailAddress":"[email protected]"},{"AdminID":2,"AdminDisplayName":"wendy","AdminEmailAddress":"[email protected]"}];


码:

循环Java语言-

<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#。

关于javascript - 如何遍历键入的Viewbag列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37436472/

10-13 03:27