【问题标题】:How to loop through a typed Viewbag list?如何遍历键入的 Viewbag 列表?
【发布时间】:2016-09-23 00:26:55
【问题描述】:

我已经通过 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":"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; }

}

【问题讨论】:

  • adminUserList 的值是多少?
  • @JohnMc 我发布了上面列表的值?

标签: javascript asp.net list for-loop document-ready


【解决方案1】:

在一行

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

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

【讨论】:

  • for 循环现在正在工作,因为我通过在其中放置警报进行了测试。但是在调试时该脚本中的 if 条件失败。我还不能得到一个明确的原因。有什么想法吗?
  • 怎么失败了?
  • 我无法判断,因为断点不会在 if 条件下触发。我看到在 for 循环中的警报之后没有代码触发。
  • 这看起来不对... if (currentUser == adminUserList.AdminDisplayName[i]) 应该是 if (currentUser == adminUserList[i].AdminDisplayName) 吗?
  • 我的错误是我把索引放错了位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
相关资源
最近更新 更多