Guide: Looping through a typed Viewbag array - best practices

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; }

}

Answer №1

When writing the code

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

It is important to remember to utilize the JavaScript adminUserList.length instead of the C# adminUserList.Count, as adminUserList is a variable in JavaScript, not in C#.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Re-activate video playback after 30 seconds of user inactivity (using RxJs)

My intention is to provide a brief explanation of the functionality I am looking for. Essentially, when a video is playing, I want it to pause if a user clicks on it, allowing them to do something else. Then, after 30 seconds of idle time, I need the video ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

Modify the data values and reconstruct the JSON structure using Python

I'm facing a situation where I need to work with the following json data: data = { "app": [ { "ida": 10, "configur": { "config": [ { "active": "true", "tol": ...

The function 'compilation.emitAsset' is not recognized by the sitemap-webpack-plugin

I'm currently working on setting up a sitemap for my live environment and I've encountered an issue while trying to utilize the sitemap-webpack-plugin. The error message I received is as follows: ERROR in TypeError: compilation.emitAsset is not a ...

Error encountered in clientside js file: Node.js indicates that 'require' is not defined

In my JavaScript file, I have important data that needs to be saved into a Mongoose schema and then inserted into a MongoDB table. The schema is stored in a separate directory, so I attempted to import it by adding the following line at the beginning of th ...

How can you pause a YouTube video using jQuery?

My custom jQuery slider consists of three panels that slide smoothly by adjusting their left CSS values. Everything works perfectly, except for one issue - I have a YouTube video embedded in one of the slides, and it continues playing even when the slide i ...

Inline checkbox label with Bootstrap 5 styling

How can I align the checkbox with its label? Example <div class="row g-1 border-bottom p-3"> <div class="col border-end justify-content-center d-flex align-items-center"> <div class="h6 text-sm-center h-25&quo ...

The node-transmission package seems to be malfunctioning

Recently, I attempted to install a package from this GitHub repository: https://github.com/FLYBYME/node-transmission on my local Node.js setup. However, upon running the example.js file provided in the repository, I encountered the following error: Error: ...

Implementing image caching in tvOS with React-Native: A step-by-step guide

Looking to Implement Image Caching in tvOS using React Native I'm trying to figure out how to cache images that I download from the internet on my Apple TV. I've experimented with various libraries, but none seem to be compatible with tvOS. Any ...

Discovering the failing dependency that isn't loading

I encountered an error while attempting to run a web application: Exception information: Exception type: ConfigurationErrorsException Exception message: Could not load file or assembly 'Atalasoft.dotImage.AdvancedDocClean.DLL' or one o ...

Eliminating bottom section in HTML/CSS

I've got this code snippet: new WOW().init(); /* AUTHOR LINK */ $('.about-me-img img, .authorWindowWrapper').hover(function() { $('.authorWindowWrapper').stop().fadeIn('fast').find('p').addClass('tr ...

Using Ajax with Laravel

Currently, I am attempting to utilize Ajax in Laravel in order to display search results in the "search_results_div" div without requiring the user to navigate away from the page. Unfortunately, I have encountered the following error message: "Column not ...

Exploring innovative designs for asynchronous JavaScript programming

Imagine you have an Express app and you need to retrieve data from a database to display on the frontend. There's a function in your code that looks like this (using node-mysql for handling database queries) exports.getData = function() { ...

Efficiently Displaying Multiple HTML Elements in React Native WebView

I am currently working on developing an Epub reader in React Native and facing a challenge. I need to find a way to efficiently transfer multiple html content files from the Epub container to the webview in order to achieve seamless pagination. ...

Steps for obtaining the current state array post re-ordering column in Angular datatables

I am facing an interesting scenario where I can successfully retrieve the current state of an array of columns using pure JS + jQuery, but unfortunately, the same approach does not seem to work in Angular 12! Despite going through the documentation for Ang ...

What is the reason behind JavaScript libraries opting for a structure of [{ }] when using JSON?

I have been experimenting with various Javascript libraries, and I've noticed that many of them require input in the format: [{"foo": "bar", "12": "true"}] As stated on json.org: Therefore, we are sending an object within an array. With this observ ...

Error: The property 'match' is undefined and cannot be read by Object.j during rendering in angular-datatables.min.js at line 6

I am currently using angular-datatables.min.js for my data table, but I have encountered an error that I have been unable to resolve. Is there anyone who can provide assistance with this issue? App.controller('DailyTaskListController', ['$s ...

JavaScript is not designed to run a second time

Currently, I have a script set up using $(document).ready(). It works perfectly upon initial loading. However, I also need this script to execute whenever the user changes an HTML select control. Ideally, upon page load, I want the filter and sort functio ...

Guide on how to call a function in ascx code-behind using JavaScript within the framework of DotNetN

Currently, I am facing an issue with my module that involves submitting data to a SQL table in a database using code behind. My validation is done through javascript, and when a button is clicked and the data is valid, a div is displayed. However, the pr ...

Discovering the presence of a component in Angular 1.5

Link to embedded content $injector.has('myMessageDirective') is returning true, while $injector.has('myMessageComponent') is not. Has anyone else encountered this issue or found a solution? I am concerned that my components may not be ...