我已通过Viewbag将List<AdminUsers>
传递给视图。然后将该列表分配给javascript var并循环播放。
但是在视图调试期间,这个for循环永远不会循环,虽然我已经设置了一个断点。
循环的目的是检查adminUserList
中的任何用户是否与当前登录的用户匹配。 currentUser
也是init,因此排除此值为空。
为了调试原因。我测试了Viewbag.AdminUserList
已分配,并且在控制器中是init。我还在此列表的视图中设置了一个警报,它是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 loop -
<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; }
}
答案 0 :(得分:2)
在第
行for (var i = 0; i < adminUserList.Count; i++)
您需要使用JavaScript adminUserList.length
而不是C#adminUserList.Count
,因为adminUserList
是JavaScript变量而不是C#。