Cannot use returned list from ajax call

I'm trying to get a list with an AJAX call for a C # method and display its elements using jQuery, but I can't do this. Here is what I got:

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

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

This works as expected, and I get a warning with the string 'test ok'. However, if I try to return a list, I cannot go through it in 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);               
    }
});

Using this code, I get the following error:

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

Hope you help me, thanks.

+4
source share
4 answers

Json JsonRequestBehavior.AllowGet, , JsonRequestBehavior 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); 
});

success error , .done fail

+8

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);               
    }
});
+1

, Json:

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

, JsonResult #. JsonResult , ASP.NET MVC, .

Just use a dictionary in C # to return a KeyValuePair collection

0
source

All Articles