generate an array using JavaScript and Html.action

I'm struggling with creating an array of strings in JavaScript using a function within my MVC controller. The current approach is not yielding the desired results, and I'm unsure of the necessary steps to rectify this issue. Below, you'll find both my JavaScript and controller code. Any assistance would be greatly appreciated.

JavaScript:

var optionString = @Html.Action("PopulateDashboardDropdown", "Embed", new { Dashboards = Model[0][0].Dashboards });

Controller:

public string[] PopulateDashboardDropdown(ODataResponseListDashboard[] dashboards)
    {
        string email = "";
        //Code to find the groupID for the current user
        foreach (Claim claim in ClaimsPrincipal.Current.Claims)
        {
            if (claim.Type == "emails")
            {
                email = claim.Value;
                email = email.ToLower();
            }
        }
        string[] orgs = GetOrgs(email);
        string[] retVal = new string[orgs.Length];
        bool[] admin = new bool[orgs.Length];
        for (int i = 0; i < orgs.Length; i++)
        {
            admin[i] = isAdmin(orgs[i], email);
            retVal[i] = "";
        }

        //Code to construct a dropdown selector based on dashboard names
        for (int i = 0; i < orgs.Length; i++)
        {
            for (int j = 0; j < dashboards[i].Value.Count; j++)
            {
                if (dashboards[i].Value.ElementAtOrDefault(j).DisplayName.Contains("Admin"))
                {
                    if (admin[i])
                    {
                        retVal[i] += "<option>" + dashboards[i].Value.ElementAtOrDefault(j).DisplayName + "</option>";
                    }
                }
                else
                {
                    retVal[i] += "<option>" + dashboards[i].Value.ElementAtOrDefault(j).DisplayName + "</option>";
                }
            }
        }
        return retVal;
    }

Answer №1

It appears that there may be some issues in the code without a clear description of the error. Here are a couple of suggestions to resolve the issues:

1) Modify the controller method to return a JsonResult:

public JsonResult PopulateDashboardDropdown(ODataResponseListDashboard[] dashboards)
{
    ...
    return this.Json(retVal);
}

2) Retrieve data using an ajax call (make sure to include the correct URL in http format as Http.Action/Razor will not function in JavaScript):

$.getJSON(myUrl, function (data) {  
   var optionString = data;       
   ...
});

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

Add distinctive formatting for the final element that is not the last child

Presented with a fascinating challenge, I find myself with an ever-changing number of .child.red children. I am in need of referencing the last .child.red element dynamically using styles. Although I have attempted to achieve this on my own, I am curious a ...

Organize a list using custom span values with JavaScript

<ul id="CoreWebsiteTopHeader_6_list"><li><a class="navigation" href="/seller"><span class="editableLinks" data-id="32638" data-sort="110">Seller</span></a></li><li><a class="navigation" href="/about">&l ...

Testing the performance of MEAN applications under heavy load

As I work on developing an application using the cutting-edge MEAN stack, I have successfully deployed the initial version to a server. This application comprises of a static HTML file (along with CSS and some images) as well as numerous JavaScript files. ...

Utilizing ObjectLoader for loading JSON featuring a BufferGeometry with multiple materials is not successful

I have successfully crafted a sphere using multiple materials in the following manner: const materials = [ new THREE.MeshPhongMaterial({}); new THREE.ShaderMaterial({ visible: false}); ] const geometry = new THREE.SphereBufferGeometry(2,100,100); ...

Pressing the enter key will submit the form

After receiving feedback from users in my live chat room, one common request was to add a feature that allows them to send a message by pressing the enter button, instead of creating a new line in the text box. Despite attempting to implement some jQuery ...

Show the viewModel list only if the ids in the list match the chosen id selected by the user

I am currently working on developing an MVC application using vb.net that will showcase an issue along with its corresponding comments. The issue data is stored in a table called IssueTable and has a one-to-many relationship with the commentsTable. I am fa ...

perform one task following the completion of another

Can I run the second function after the first one without using a timeout event in this JavaScript code: if (direction !== "leftnav") { // DO THINGS }; setTimeout(function () { //DO OTHER THINGS AFTER THE FIRST THING }, 1000); Your input is greatly app ...

Trouble is arising in rendering events with years before 100 (specifically years 0000 - 0099) when using the ISO8601 format in fullCalendar

I've created a Calendar that showcases various events using fullcalendar. The events span from the years 0001 to 6000. Fullcalendar requires dates in ISO8601 format, and I am providing them as such. Events from the years 0100-6000 render perfectly w ...

How to send parameters to the jquery .css() method

I'm attempting to create hyperlinks that can dynamically set inline styles for different elements on a webpage. I have managed to save the element and attribute settings in hidden span elements and retrieve them to display in an alert dialog. However, ...

help with categorizing exams

Currently, I am working on creating unit tests for a .NET C# library that I developed. One of the classes I am testing is a cache provider class which acts as an abstraction layer for the distributed cache - AppFabric. As I navigate through the process of ...

When navigating to '/blogs/', the index.js file in Next.js will automatically open

I'm working on a project using next.js and I want to ensure that when I visit 'localhost:3000/blogs/', it opens the index.js page. The index.js file is located in the 'blogs' folder of my project. Currently, it does open properly ...

What is the best way to send an array as a reference to a function?

I am working on a function where an array pointer is passed to modify elements in the array: (void) updateArray:(Byte[])changingArray { // make changes to changingArray } The array in question is of type Byte, but I am uncertain if I have used the corr ...

Numbering each numeral

Looking to add a sequence number next to each digit using jQuery or JavaScript: If I enter the following numbers: 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 9, 10 and so on then the desired output should be: 1.1, 1.2, 1.3, 2.1, 3.1, 4.1, 5.1, 5.2, 5.3, 6.1 ...

Error message: A boolean type cannot be used as a function in the fullcalendar ajax call

I have successfully implemented a fullcalendar into my app and have added a method to filter results by user: function filterEventsByProvider(selected_provider) { $('#calendar').fullCalendar('removeEvents'); $('#calendar&a ...

Communicate through Node.js, with messages that multiply based on the total number of users currently in the chat room

Currently, I am working on a project that involves creating a chat application using Node.js. However, I have run into an issue where the message gets repeated for each user in the chat. For example, if there are 4 users in the chat, the message will be di ...

In certain situations, the JavaScript code runs either before or after the print dialog is displayed when using the window

I am facing an issue with the print function on my web page. I want to display a thank you message to the user after they have either printed or cancelled the print dialog. Below is a simplified version of the print function code: function printThenThank ...

Transferring an object from Javascript to C++/CX following a C++/CX interface in Windows Runtime Components

As a newcomer to Windows Runtime Component, I've been exploring ways to accomplish the following task. I'm looking to extend a C++ interface in JavaScript. namespace MySDK { public interface class LoggerPlugin { public: virt ...

What is the best way to implement an alert box in MVC without triggering a page redirection?

I have a specific requirement to display a custom alert box in order to confirm the user's intention to delete an item. Once the item is deleted, another alert box should appear confirming that the deletion was successful, prompting the user to click ...

Unable to activate the 'Click' function in Angular/Typescript after selecting element with 'document.querySelector'

In my Angular 8 Project, there is an element on a page with a unique string attached to the attribute 'data-convo-id'. This element has a click function that loads data based on the data attribute specified above. However, without direct access ...

Incorporating PHP generated content into Dart without using Ajax

My current website is built using PHP (Laravel) on the server side and Javascript on the client side. Now, I am interested in replacing the Javascript with Dart. Currently, I inject data into the Javascript on the webpage like this: <script> va ...