How to send list of string in Ajax call

You can send a list of strings in an Ajax call by serializing the list as JSON and passing it as the `data` parameter in the Ajax request. Here's an example:

var list = ["apple", "banana", "orange"];
$.ajax({
    url: "/Controller/Action",
    type: "POST",
    data: JSON.stringify(list),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(result) {
        // handle success
    },
    error: function(xhr, status, error) {
        // handle error
    }

});

In this example, the `list` variable contains an array of strings that you want to send to the server. The `$.ajax()` function is then used to send the array to the controller action method.

The `JSON.stringify(list)` function is used to serialize the list as a JSON string that can be sent in the request. The `contentType` parameter is set to `"application/json; charset=utf-8"` to indicate that the data being sent is JSON. The `dataType` parameter is set to `"json"` to indicate that the expected response type is JSON.

In the controller action method, you can receive the list of strings as a parameter. The parameter should be annotated with the `[FromBody]` attribute to indicate that the data is coming from the request body. Here's an example of how to receive the list of strings in the controller action method:

[HttpPost]

public ActionResult ActionName([FromBody] List<string> list)

{

    // process the list of strings

    return View();

}

In this example, the `ActionName` method is decorated with the `[HttpPost]` attribute to indicate that it should be called when an HTTP POST request is received. The `List<string>` parameter is used to receive the list of strings, and the `[FromBody]` attribute is used to indicate that the data is coming from the request body. You can then process the list of strings as needed and return a view.

Previous Post Next Post