data argument cannot accept an array entry - internal server issue

My attempt to call a C# MVC controller method from a custom JavaScript script using Ajax seems to be encountering an issue with accepting array entries as arguments within the Ajax request.

I tested assigning them to non-array variables, which worked, but I specifically need to pass them as array elements.

public async Task<ActionResult> CallEngineAsync(int id, string command)
{
    string path = Server.MapPath("/PluginDLLs/");

    string output = await EngineBroker.CallEngine(command, path, AppDomain.CurrentDomain);

   // Session["output"] = output;
   // Session["calledPlugin"] = id;

    var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Home");
    return Json(new { Url = redirectUrl });
}
var pluginIDs = [];
var pluginCommands = [];
var pluginIntervals = [];

$(".p-container").find(".p").each(function ()
{
    var confi = $(this).find("#command").attr("value");

    var interval = 1000 * confi.replace(/\D/g, '');

    if (confi.includes("interval") && interval > 0)
    {
        var id = $(this).attr("data-pluginid");
        pluginIDs.push(id);

        pluginCommands.push(confi);

        pluginIntervals.push(interval);
    }
});

for (let p = 0; p < pluginIDs.length; p++)
{
    window.setInterval(function ()
    {
        $.ajax(
        {
            url: 'Home/CallEngineAsync',
            data: { id: pluginIDs[p], command: pluginCommands[p] },
            traditional: true,
            type: 'POST',

            success: function (data)
            {
                window.location.href = data.Url;
            },

            error: function (xhr, status, error) { }
        });

    }, pluginIntervals[p]);
}

The error message received states: POST https://localhost:44381/Home/CallEngineAsync 500 (Internal Server Error)

Answer №1

Could you switch the method from POST to GET? After that, insert the following code snippet:

return Json(new { RedirectUrl = url }, JsonRequestBehavior.AllowGet);

Additionally, update the following line of code:

public async Task<JsonResult> ExecuteAsync(int identifier, string action)

Answer №2

It turned out to be a scope issue in the end: variables used within setInterval() needed to be declared in the same scope, and the p (counter) was consistently being set to the final value prematurely due to the timeout. Additionally, a change was required in the C# method in order to properly retrieve arguments:

public async Task<string> UpdateEngineAsync([FromBody] int id, [FromBody] string command)
        {
            string path = Server.MapPath("/PluginDLLs/");

            string result = await EngineBroker.UpdateEngine(command, path, AppDomain.CurrentDomain);

            Session["result" + id] = result;

            return result;
        }


$(".p-container").find(".p").each(function ()
{
    var config = $(this).find("#command").attr("value");

    var interval = 1000 * config.replace(/\D/g, '');

    if (config.includes("interval") && interval > 0)
    {
        var id = $(this).attr("data-pluginid");

        var output = $(this).find("#" + id)

        window.setInterval(function ()
        {
            $.ajax(
            {
                url: 'Home/UpdateEngineAsync',
                data: 'id=' + id + '&command=' + config,
                traditional: true,
                type: 'GET',

                success: function (response) 
                {
                    output.html('<h4><br />' + response + '</h4>');
                    //window.location.href = response.Url
                },
            });
        }, interval);
    }
});

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

Utilizing Oracle DBMS_ALERT in Oracle APEX: A Beginner's Guide

On Oracle APEX 4.2, I have set up a page process that utilizes DBMS_ALERT for a long-running task that could potentially last up to a minute. As the process is executing, notifications about its progress are being triggered using DBMS_ALERT.signal. My qu ...

Retrieve a collection of Vue components

My single page website has a simple component structure: <template> <div id="app"> <header /> <section-about /> <section-warranty /> <section-advantages /> <section-service /> <section ...

Can we dynamically apply a class to the body depending on the domain in the window's URL?

Currently, I am developing a website for a company that has operations in both New Zealand and Australia. They have domains pointed to the same website with both .co.nz and .com.au extensions. I have written the following code to assign the class "austral ...

Encountering a KeyError while implementing a search view with Django and AJAX

I'm in the process of enhancing my Django blog application by integrating an AJAX search feature. Below is the code snippet: search_form.html <form id="search-form" method="get" action="{% url 'search' %}"> <input type="text" ...

The appearance of responsive CSS is altered when deployed compared to when it is viewed on the

I'm a beginner in web development and facing an issue with my mobile CSS. The strange thing is that when I view it on localhost, everything looks great, but once deployed (tried both Heroku and GitHub), it appears distorted. Even when I make extreme c ...

How to Use C# and Selenium to Precisely Position the Mouse Cursor at a Certain Location or Element

Currently, I am trying to perform a click operation using Selenium and C#. While I am able to successfully execute the click operation, I am unable to move the mouse pointer (cursor) to a specific coordinate or over a specific element. I have implemented ...

Chrome debugging tool does not refresh page source

This issue has been lingering for quite some time and despite similar questions, I have not come across a satisfactory solution. The problem lies in the fact that the SOURCE used to step through the code does not refresh with every page load. Disabling the ...

Having trouble configuring the default download folder in Chrome

I am encountering an issue with setting the default download folder for the Chrome driver. I have researched various solutions, but none of them seem to be effective. Here are the methods I have attempted: var options = new ChromeOptionsWithPrefs(); opti ...

"Embedding social content within an iframe may result in the element being unresponsive

I have a setup where I'm utilizing social embed to include Instagram content in the footer. When I insert the provided iframe code, the layout looks correct but the content is not clickable. <iframe src="https://embedsocial.com/facebook_album ...

React JS: Component failing to render

My react component is not rendering and I can't find any bugs. The problem arises when I set the isLoggedIn state to "true", resulting in my HeroSlide not rendering If isLoggedin = false, then: https://i.sstatic.net/JoDSn.jpg If isLoggedIn = true, t ...

Tips for stopping Vue.js automatic merging of CSS classes

Recently, I embarked on my journey with Vue.js and have been thoroughly enjoying the experience. However, I've stumbled upon a challenge that has me stumped. Despite searching high and low and studying the documentation, I haven't found a solutio ...

Is there a way to display points on each vertex of my geometry using React, three.js, and Three-React-fiber?

I'm trying to figure out how to utilize the pointsmaterial and points object within three-react-fiber. Currently, I have a custom geometry that I've imported from a .gltf file and I'm rendering it like this: <mesh castShadow recei ...

Issues encountered while attempting to update data in angular2-datatable

Once the datatable has been rendered, I am facing an issue where I cannot update the data. I'm utilizing angular2-datatable. In my appcomponent.html file: If I try to update 'data2' in my appcomponent.ts file as shown below: this.httpserv ...

Should information be retrieved from the server or the client side?

Allow me to clarify the situation at hand. I am currently developing a website where users can store movie information, sourced from a third-party API known as The Movie Database. At this juncture, my main concern pertains to optimizing performance throu ...

Hide the div when hovering occurs

I need a way to hide the 'sample' div when hovering over it and then show it again when the mouse moves away $('.secmenu').hover(function() { $('.sample').css('opacity', '0'); if ($('.secmenu&a ...

The AngularJs project is currently experiencing issues when trying to function as a single page web application

I'm currently working on incorporating AngularJS into an existing web project that uses jQuery. Here is a snippet of my code: <div class="medya" ng-repeat="d in data" masonry-item-dir> <a href="{{d.Url}}" class="onizleme"><img src="{ ...

Attempting to loop through a list and create a retrieval function for each item

My goal is to loop through the style tags and create a GET function for each one. The issue I'm facing is that the GET function is being written with a direct reference to 'styleTags[i]' instead of converting it to the appropriate tag. var ...

Tips for swapping out the data array in my ChartJS graph

I am currently working on a project that involves changing the data array of a chart with a completely different one. Unfortunately, although my code is successfully updating the labels of the chart, the data itself remains unchanged and I cannot figure ou ...

Dynamic Code for Removing List Items Based on Date

I need assistance in resolving an issue with my company's website design and function. Specifically, I am working on a page that displays a list of events where employees will be present throughout the year. Here is an example: <div class="contai ...

Integrating individual script into HTML

Imagine you have a file named public/index.html. Additionally, there is another html file called otherScript, which contains only <script> tags with a script inside. How can you include these scripts into your public/index.html file? You intend to ...