user616076
user616076

Reputation: 4001

Why is my List<string> not returning from MVC Controller from $ajax call

I'm trying to create bespoke lists in my cshtml file using an ajax call

.ajax({
        type: "GET",
        cache: false,
        url: "@Url.Action("getValidationLists")",
        contentType: "application/json",
        dataType: "json",
        success: function (result) {                
            var list = result.list;
            $.each(list, function (index, value) {
                alert(value);
            });
        }
    });       

The Controller then collects the data puts it in a List and returns it to my cshtml file using json format. the controller method is below

[HttpGet]
[Authorize]
public JsonResult getValidationLists()
{
    List<List<String>> validList = new List<List<String>>();
    List<UIReferenceData> results = AddErrorsToModelState<List<UIReferenceData>>(_StaticDataServiceAgent.GetAllAssetTypes());
    for (int i = 0; i < results.Count; i++)
    {
        List<String> resultList = new List<String>();
        string id = results[i].ID.ToString();
        string name = results[i].Name;
        resultList.Add(id);
        resultList.Add(name);
        validList.Add(resultList);
    }
    return Json(new
    {
        validList = validList
    }, JsonRequestBehavior.AllowGet);
}

I've tried several different versions but the returning code never gets as far as the alert(value); code. What am i missing?

Upvotes: 0

Views: 719

Answers (2)

Shyju
Shyju

Reputation: 218732

The JSON response you are returning from your action method looks like this

{
    "validList": [      
        ["1", "SomeText"],
        ["2", "SomeText"],
        ["3", " SomeText"]
    ]
}

Your response has a validList property which is an array and each item in an array is again another array with 2 items.

This should work

 success: function (result) {           
     $.each(result.validList, function (index, value) {
       console.log(value[0]);
       console.log(value[1]);
    });
 }

Upvotes: 0

hutchonoid
hutchonoid

Reputation: 33306

The property name is inconsistent with what you are returning from your action:

var list = result.list;

Should be:

var list = result.validList;

However you are returning a List<List<String>> rather than a List<String> too.

I think you need to address both of the above in order to fix.

Upvotes: 1

Related Questions