将字符串数组从MVC返回到jQuery ASP.NET

dee*_*tes 6 arrays asp.net-mvc jquery system.array

我想通过jQuery AJAX调用从MVC函数返回一个字符串数组.

我的客户端代码是:

function get_categories() {
    var url = "/Profile/GetCharacters";
    $.post(url, function (data) {
    alert(data);
});
Run Code Online (Sandbox Code Playgroud)

但我无法读取数组元素.在alert(data)它总是说,system.array[] 并在alert(data[0])其中说s(即system.array []中的第一个字符)而不是数组元素.

这是我的服务器端代码的简化版.原因是原来很复杂:)

public Array GetCharacters()
    {

        var ret = new string[10];
        ret[0]="abc";
        ret[1] = "def";
        ret[2] = "ghi";
        return (ret);
    }
Run Code Online (Sandbox Code Playgroud)

但这会给"System.string []"而不是访问单个值时的相同问题

Mat*_*ttW 14

您可以返回JSON.

例如,您可以向以下控制器操作发出Ajax请求:

public JsonResult GetMyData()
{
    SomeClass s = new SomeClass();
    s.Property1 = "value";
    s.Property2 = "another value";

    return Json(s, JsonRequestBehavior.AllowGet); //you will need the AllowGet option to return data to a GET request
}
Run Code Online (Sandbox Code Playgroud)

然后,您的javascript可以向控制器发出Ajax请求(使用jQuery的Ajax函数):

var onSuccess = function (data) {
    //data will be your s object, in JSON format
};

$.ajax({
    type: 'GET',
    url: '/ControllerName/GetMyData/',
    success: function (data) { onSuccess(data); }
});
Run Code Online (Sandbox Code Playgroud)

编辑:当返回一个数组或List时,你需要在Ajax调用中添加传统:true选项,如下所示:

var onSuccess = function (data) {
    //data will be your s object, in JSON format
};

$.ajax({
    type: 'GET',
    url: '/ControllerName/GetMyData/',
    success: function (data) { onSuccess(data); },
    traditional: true
});
Run Code Online (Sandbox Code Playgroud)

我不是百分百肯定为什么(我确定有人会填补我们),但这让我适应了过去.

还有一个编辑:你可能需要解析JSON,它应该为你创建一个真正的javascript数组对象:

var onSuccess = function (data) {
    //data will be your s object, in JSON format
    var arr = JSON.parse(data);
};
Run Code Online (Sandbox Code Playgroud)