How to pass a list of integer from js to c# controller

Forums JavaScriptHow to pass a list of integer from js to c# controller
Staff asked 1 year ago

Answers (2)

Add Answer
Umang Ramani Marked As Accepted
Staff answered 1 year ago

To pass a list of integers from JavaScript to a C# controller in ASP.NET MVC, you can use the following steps:

  1. Define an array of integers in JavaScript: First, you need to define an array of integers in JavaScript that you want to pass to the controller.

For example:

var myList = [1, 2, 3, 4, 5];
  1. Convert the array to a JSON string: Convert the array of integers to a JSON string using the JSON.stringify() method.
var jsonString = JSON.stringify(myList);

 

  1. Make an AJAX request to the C# controller: Use the $.ajax() method or any other AJAX method to make a POST request to the C# controller action.

For example:

$.ajax({
  type: 'POST',
  url: '/MyController/MyAction',
  contentType: 'application/json',
  data: jsonString,
  success: function(result) {
    // Handle the response from the controller
  },
  error: function(xhr, textStatus, errorThrown) {
    console.error('Error:', errorThrown);
  }
});

 

  1. Define the C# controller action: In the C# controller, define an action that accepts a list of integers as a parameter.

For example:

[HttpPost]
public ActionResult MyAction(List<int> myList)
{
    // Do something with the list of integers
    return View();
}

 

In this example, the MyAction method accepts a list of integers as a parameter named myList. When the AJAX request is made to the /MyController/MyAction URL, it will call the MyAction method on the controller and pass in the deserialized list of integers.

Note: When making an AJAX request to a C# controller, it’s important to set the contentType property of the AJAX request to application/json to indicate that the data being sent to the server is in JSON format. Additionally, the data property of the AJAX request should be set to the JSON string of the data being sent to the server.

Staff answered 1 year ago

you can use AJAX (Asynchronous JavaScript and XML) to send an HTTP request to the controller

For Example :

var integerList = [1, 2, 3, 4, 5]; 
$.ajax({
    type: "POST",
    url: "/Controller/GetData",
    data: { integerList: integerList },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        // Handle your response from the controller
    },
    error: function (xhr, ajaxOptions, thrownError) {
        // This is Handle errors portion
    }
});

In C# controller  add below method for accept AJAX Call

public ActionResult GetData(List<int> integerList)
{
    // Do something with the list of integers
    return View();
}

 

Subscribe

Select Categories