Christian Agius
Christian Agius

Reputation: 309

Pass Array from MVC Controller to Javascript

is it possible to read the contents of an array that is passed from an MVC Controller to JavaScript?

This is a method in my controller that returns an array. (tried with a list before but didn't succeed)

public string[] GetAllEvents() 
{
    string[] array = new string[2];
    array[0] = "a";
    array[1] = "b";

    List<string> lst = new List<string>();
    lst.Add("a");
    lst.Add("b");
    return array;
}

Here is the JavaScript function from which I'm calling the Controller method.

function GetAllEvents() {
    $.ajax({
        type: "GET",
        url: "/Service/GetAllEvents",
        success: function (result) {
            alert(result.toString() + "  " + result[0]);
        },
        error: function (req, status, error) {
            //alert("Error");
        }
    });
};

The result is a System.String[] and the result[0] is giving me 'S' as a result.

Upvotes: 2

Views: 4802

Answers (1)

SLaks
SLaks

Reputation: 887453

MVC actions should return ActionResults.

You can then return Json(list, JsonRequestBehavior.AllowGet) and it will work.

Upvotes: 4

Related Questions