简体   繁体   中英

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.

MVC actions should return ActionResult s.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM