无法使用来自ajax调用的返回列表

时间:2013-11-02 00:18:29

标签: c# jquery ajax asp.net-mvc

我正在尝试获取一个带有对C#方法的AJAX调用的列表,并使用jQuery显示其项目,但我无法做到。这是我得到的:

public string test()
{
    return "test ok";            
}

$.ajax({
    type: "POST",
    url: "Computer/test",
    success: function (data) {
        alert(data);
    },
    error: function () {
        alert("error");
    }
});

这按预期工作,我收到'test ok'字符串的警报。但是,如果我尝试返回一个列表,我无法在jquery中遍历它。

public List<string> testList()
{
    List<string> test = new List<string>;
    test.Add("test1");
    test.Add("test2");
    return test;
}

$.ajax({
    type: "POST",
    url: "Computer/testList",
    dataType: "json",
    success: function (data) {
        var list = data.d;
        $.each(list, function (index, item) {
            alert(item);
        });
    },
    error: function (xhr) {
        alert(xhr.responseText);               
    }
});

使用此代码,我收到以下错误:

  

System.Collections.Generic.List`1 [System.String]

希望你能帮助我,谢谢。

4 个答案:

答案 0 :(得分:10)

Json的服务器端使用JsonRequestBehavior.AllowGet,查看我们必须在Why is JsonRequestBehavior needed?使用JsonRequestBehavior的原因:

public JsonResult testList()
{
    List<string> test = new List<string>;
    test.Add("test1");
    test.Add("test2");
    return Json(test,JsonRequestBehavior.AllowGet);
}

你JS:

$.ajax({
    type: "POST",
    url: "Computer/testList",
    dataType: "json"
})
.done(function(data){
   var list = data;
   $.each(list, function (index, item) {
       alert(item);
   });
})
.fail(function(xhr){
    alert(xhr.responseText); 
});

successerror已弃用,请改用.donefail

答案 1 :(得分:1)

更改控制器操作以返回Json:

public JsonResult testList()
{
    List<string> test = new List<string>;
    test.Add("test1");
    test.Add("test2");
    return Json(test);
}

答案 2 :(得分:1)

尝试使用返回类型ActionResult,通过Json()方法返回JSON数据,如下所示:

public ActionResult testList()
{
    List<string> test = new List<string>;
    test.Add("test1");
    test.Add("test2");

    return Json(test);
}

注意:在jQuery .ajax()调用中,您不再需要data.d语法,因此您的jQuery将如下所示:

$.ajax({
    type: "POST",
    url: "Computer/testList",
    dataType: "json",
    success: function (data) {
        var list = data;
        $.each(list, function (index, item) {
            alert(item);
        });
    },
    error: function (xhr) {
        alert(xhr.responseText);               
    }
});

答案 3 :(得分:0)

首先在C#代码中使用JsonResult。 JsonResult在ASP.NET MVC中更可靠,可以返回数据。

只需在c#中使用字典即可​​返回KeyValuePair的集合

相关问题