How to return a list from AJAX method to view from controller ASP.NET MVC

Forums ASP.NET MVCHow to return a list from AJAX method to view from controller ASP.NET MVC
Staff asked 2 years ago

Answers (2)

Add Answer
Umang Ramani Marked As Accepted
Staff answered 2 years ago

To return a list from an AJAX method to a view from a controller in ASP.NET MVC, you can follow these steps:

  1. Define a controller action: First, define a controller action that returns a list of data. For example:
public ActionResult GetList()
{
    List<string> myList = new List<string> { "item1", "item2", "item3" };
    return Json(myList, JsonRequestBehavior.AllowGet);
}

 

In this example, the GetList action returns a list of strings. The Json method serializes the list to JSON format and returns it to the client.

  1. Call the controller action with AJAX: In the view, use AJAX to call the controller action and retrieve the list of data. For example:
$.ajax({
    url: '/MyController/GetList',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
        // Handle the returned data
    },
    error: function(xhr, textStatus, errorThrown) {
        console.error('Error:', errorThrown);
    }
});

In this example, the AJAX call is made to the GetList action on the MyController controller. The dataType property is set to json to indicate that the response from the server is in JSON format.

  1. Handle the returned data: In the success callback of the AJAX call, handle the returned data as needed. For example, you can iterate over the list of data and create HTML elements to display the data on the page.
success: function(data) {
    $.each(data, function(index, item) {
        var li = $('<li>').text(item);
        $('ul').append(li);
    });
}

In this example, the returned list of strings is iterated over using the $.each() method. For each string in the list, a new li element is created with the string text and appended to a ul element on the page.

Note: When returning JSON data from a controller action, it’s important to set the JsonRequestBehavior parameter of the Json method to JsonRequestBehavior.AllowGet to allow GET requests for JSON data. This prevents a security vulnerability known as JSON hijacking.

Staff answered 2 years ago

You can use return Type Json() because that returns the list as a JSON object.

First, Create an action method in your controller that returns the list of data you want to display in your view.

For example:

public ActionResult GetList()
{
    List<string> dataList = new List<string> { "Item 1", "Item 2", "Item 3" };

    return Json(dataList, JsonRequestBehavior.AllowGet);
}

This action method returns a JSON result of the dataList list.

Then In your view, create an AJAX call to the GetList  action method:

$.ajax({
    type: "GET",
    url: "@Url.Action("GetList", "ControllerName")",
    dataType: "json",
    success: function (data) {
       // use the returned data here
            console.log(data);
    },
    error: function () {
        alert("An error occurred while retrieving the list.");
    }
});

In the success function then handles the data by looping through it and appending these Listdata in console.

 

Subscribe

Select Categories