"Creating an array in JavaScript and passing it to a C# MVC controller: a step-by-step guide

Is it possible to create an array in jQuery/JavaScript and then send it to my C# controller?

I have a list of employees from a select multiple, which I can display like this:

    <div class="demo">
        <select style="display:none" id="liste" multiple="" placeholder="Select">
            @foreach (var employe in ViewBag.Employes)
            {
                <option value="@employe.ID_Employe">@employe.Name</option>
            }
        </select>
    </div>

    <a class="btn btn-default" id="check" href="#">Next</a>

Here is my script :

        $('#check').on('click', function () {
            $("#liste").find("option:selected").each(function () { alert($(this).text()); });
        });

To send the data, I use the following code :

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '/MyAjaxRoute',
            data: { arraytosend: arraybuildInJS },
            success: function (response) {
                if (response.success) {
                    alert('yes');
                }
        },
  • Could you please explain to me how to create an array in JavaScript and pass it to a C# MVC controller?

Answer №1

To start, establish an Action within your Controller:

public JsonResult HandleArrayData(List<string> arrayData)
{
   if(arrayData.Count == 0) return Json(new {success = false});

   //perform actions with arrayData
   return Json(new {success = true});
}

Next, in your JavaScript code, you can implement the following logic:

var myArray = [];
$('#check').on('click', function () {

$("#liste").find("option:selected").each(function () {
    myArray.push($(this).text)
});

$.ajax({
     type: 'POST',
     dataType: 'json',
     url: '@Url.Action("HandleArrayData", "MyController")',
     data: { arrayData: myArray },
     success: function (response) {
       if (response.success) {
          myArray = [];//clear the array, alternatively use myArray.length = 0
          alert('Success!');
       }          
     }
   });
});

Answer №2

It seems like using the push method is what you need.

var arraybuildInJS = [];
$('#check').on('click', function () {
            $("#liste").find("option:selected").each(function () { arraybuildInJS.push($(this).text()); });
        });

Keep in mind that your controller should be expecting an Enumerable of strings. If it's not coded yet, make sure the objects match up correctly.

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

Having trouble with the image compressor not being imported correctly in Next.js?

I've been attempting to compress an image, but when I try to import the ImageCompressor normally like this: import ImageCompressor from "image-compressor.js"; It throws an error: Uncaught ReferenceError: window is not defined This is the s ...

Parsing a child class from a JSON API to extract the data

I'm trying to deserialize a subclass from JSON using Xamarin (C#) Here are the classes: public class PhoneDirectory { public string name { get; set; } public string number { get; set; } } public class RootPhoneDirectory : List<PhoneDirect ...

Can a fixed position element disregard its parent?

I've been experimenting with a div that switches between position: absolute and position:fixed on scroll. You can view the issue with my code on JSFiddle: http://jsfiddle.net/g9NVj/2/ The problem areas are the pink and blue boxes that change color as ...

Experiment with using webdriverio and javascript to select checkboxes

Currently, I am experimenting with testing the selection of checkboxes using webdriverio in combination with mocha and chai. Below is an example of what I attempted utilizing a javascript module pattern select_checkbox: function(browser, key, value){ r ...

Guide to converting JSON with an array into a presenter using a collection

When I retrieve JSON data from an external service regarding trainings for my current_user via email, I receive information like this: { “id:”5357c5d17303b5357c5d173078”, “email”:”<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Upload Request Failure Due to Drag and Drop Functionality in HTML5

Recently, I implemented a drag and drop upload form on a webpage. The 'normal' file input functioned perfectly as expected when prompting for a file to be selected. However, I encountered an issue where the POST request was missing the file infor ...

Error in regular expression format

I want to extract data from a JSON format like this: {"response":[9816,{"vid":166941761,"owner_id":-460389,"title":"Хочу спиться!","description":"Вкусная группа БОРЩ - http:\/\/vk.com\/borsch<br\/ ...

Do not reload the page after a successful ajax request

I'm using an Ajax section to submit data in Laravel. I want the page to not reload if the submission is successful, but to reload if there's an error. Currently, when there is an error, the page reloads correctly. However, I'm facing an issu ...

Can the page URL be reloaded without modifying the request URL?

I have a situation where I need to activate a function that generates a PDF and opens it in a new tab when a button is clicked on a page. However, after clicking this button, I also want the current page to reload without changing the request URL so that t ...

Asynchronous requests in Node.js within an Array.forEach loop not finishing execution prior to writing a JSON file

I have developed a web scraping Node.js application that extracts job description text from multiple URLs. Currently, I am working with an array of job objects called jobObj. The code iterates through each URL, sends a request for HTML content, uses the Ch ...

Concerns regarding rendering HTML and drawing in Node.js

Having an issue where node.js is serving an html file with an SVG drawing. The index.html features a chart similar to the line chart found at http://bl.ocks.org/mbostock/3883245 Whenever I try to serve the index.html through the express server, I end up ...

triggering controller on click event in JSP

Using a spring web application, I need to call a controller in a java file from a JSP file using an ajax function. How can I achieve this? <p class="bottom-slide-corners"> <a class="billing" href="#Billing"><spri ...

Replicate the anchor's functionality (opening in a new window when 'ctl' is pressed) when submitting a form

I have a question that may seem unconventional - Is there a graceful method to replicate the functionality of an anchor tag when submitting a form? I want users to be able to hold down the control key while submitting a form and have the result open in a ...

Handling session timeout in asp.net on disconnection

On my intranet page, I am using JavaScript to prevent it from timing out indefinitely. However, I am facing an issue where the session times out when the user loses connection, which frequently occurs when moving in and out of wifi range. Is there a way ...

A guide on dynamically integrating CKEditor into Vue.js 3, exclusively for the client side

I am facing a challenge with integrating CKEditor 5 into my Vue.js 3 application, particularly in ensuring that it is only loaded on the client-side. Due to server-side rendering limitations, I need CKEditor to be included dynamically based on the browser ...

Displaying minute scale from right to left using jQuery technology

I successfully created a minute scale that is functioning well, but now I am encountering an issue with displaying my scale. Instead of being oriented left to right, I would like it to be displayed from right to left. Can anyone suggest what might be wron ...

AngularJS - Establishing communication between controller and view

I am facing an issue with the Angularjs view. I seem to be making a mistake somewhere and I can't figure out where the problem lies. I hope someone can assist me with this. The problem is that {{user.login}} (userRepoInfo.html file) is not being call ...

Can you tell me the JSONPATH symbol that signifies a mismatch with a regular expression?

My Zabbix item has the PreProcessing JSONPath as shown below: Item key: vfs.fs.get Preprocessing JSONPath script: $.[?(@.fstype =~ '{$FSTYPE.MATCHES}')] The resulting structured JSON list looks like this: [{ "fsname": "/" ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...

What is the best way to determine which watchers are triggered in Vue.js?

Within my parent component, there are numerous nested child components. Whenever a click occurs on one of the child components, it triggers an update to the route. The parent component watches the route property and performs certain actions when it change ...