Passing an Array to MVC Action via AJAX

In this blog post, we will explore the process of passing an array to an MVC action using AJAX. With a clear code example and step-by-step guide, you'll learn how to effortlessly transmit array data to MVC actions.

Code Example

Let's say we have an array of numbers that we want to pass to an MVC action. We'll use AJAX to send this array to the server.

var numbers = [1, 2, 3, 4, 5];

$.ajax({
  url: '/Controller/Action',
  type: 'POST',
  data: { numbers: numbers },
  success: function(result) {
    // Handle the response from the server
  },
  error: function() {
    // Handle any errors that occur during the AJAX request
  }
});

In the code above, we define an array called numbers containing some arbitrary values. Then, we use the $.ajax() function provided by jQuery to send an AJAX request to the server.

Let's break down the different parts of the AJAX request:

  • url: This is the URL of the MVC action we want to call. Replace 'Controller' with the actual name of your controller and 'Action' with the name of your action method.
  • type: This specifies the HTTP method to use for the request. In this case, we're using 'POST' since we want to send data to the server.
  • data: Here, we pass an object literal with the key 'numbers' and the value being the numbers array we defined earlier. This is how we send the array to the server.
  • success: This is a callback function that gets executed when the AJAX request is successful. You can use it to handle the response from the server.
  • error: This callback function is called when an error occurs during the AJAX request. It allows you to handle any errors that may happen.

MVC Action

Now that we know how to send the array from the client to the server, let's take a look at how we can receive it in the MVC action.

[HttpPost]
public ActionResult Action(int[] numbers)
{
  // Do something with the numbers array
  return Json(new { success = true });
}

In the code above, we define an MVC action with the [HttpPost] attribute to indicate that it should be called when an HTTP POST request is made. The action takes an int[] parameter called numbers, which will automatically bind to the array we sent from the client.

Inside the action, you can do whatever processing you need with the numbers array. In this example, we simply return a JSON object with a success property set to true to indicate that the action was executed successfully.

 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice