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

Time:08-28

I want to get a list from my controller and return this list to the view.

So far, I have this:

function getNames(_id, _name) {

$.ajax({
    type: 'Post',
    url: 'GetNames/',
    data: { id: _id, name: _name},
    success: function (listName) {
        listNames = JSON.parse(listName);
    },
    error: function (response) {
        alert(response.responseText);
    }
});

}

With this I get the list of names that I want. However, this script is being done on a separate js file and I'm not being able to use it in my html.

In the html I want a for loop that loops through that listNames but when I try to use listNames it says that it doesn't exist

CodePudding user response:

In your javascript, the $.ajax settings for success and error are for creating callback functions. Those functions will be called after the AJAX response is received. I'd recommend checking out the docs for more details. https://api.jquery.com/jquery.ajax/

But don't worry, you are headed in the right direction! In the example below, doStuffWithNames will be called after you get a successful response. Inside doStuffWithNames, you can loop through the elements in that array and make whatever UI changes you'd like.

A helpful tool for working out things like this in javascript is utilizing the console.log feature. In this example, you'll see that the getNames function will [very likely] exit before your ajax response returns.

var _isDebugMode = true;
var _listNames = [];

function doStuffWithNames(listNames){
    debugConsoleLog('doStuffWithNames start');
    //TODO: loop through items and do stuff
    debugConsoleLog('doStuffWithNames end');
}

function getNames(id, name) {
    debugConsoleLog('getNames start');
    $.ajax({
        type: 'POST',
        url: 'GetNames/',
        data: { id: id, name: name},
        success: function (response) {
            _listNames = JSON.parse(response);
            doStuffWithNames(_listNames);
        },
        error: function (err) {
            //TODO: error handling
        }
    });
    debugConsoleLog('getNames end');
}

function debugConsoleLog(message){
    if(_isDebugMode)
        console.log(message);
}

I hope that helps!

  • Related