I have passed a List<AdminUsers>
through the Viewbag to a view. This list is then assigned to a JavaScript variable and looped through.
However, when debugging on the view, I noticed that the for loop is not being executed, even though I set a breakpoint on it.
The purpose of the loop is to check if any of the users in the adminUserList
match the currently logged-in user. The currentUser
is initialized so that rules out the possibility of this value being null.
To debug this issue further, I tested whether the Viewbag.AdminUserList
is properly assigned and initialized in the controller, which it is. I also added an alert in the view to confirm that this list is indeed initialized.
Question:
Does anyone know why the following for loop
is not getting called in JavaScript?
This is the value of the JS adminUserList during debugging:
var adminUserList = [{"AdminID":1,"AdminDisplayName":"brianb","AdminEmailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="50322239313e10243523247e333f3f">[email protected]</a>"},{"AdminID":2,"AdminDisplayName":"wendy","AdminEmailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d7a686369744d79687e79236e6666">[email protected]</a>"}];
Code:
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>
Controller Index method -
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");
}
Model - AdminUsers:
public class AdminUsers
{
public int AdminID { get; set; }
public string AdminDisplayName { get; set; }
public string AdminEmailAddress { get; set; }
}