Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return JSON from MVC via AJAX

I've been using a hard coded JSON object:

var resuts = [{id: 1, Code: "Code A"}, {id: 2, Code: "Code B"}]

I'm then iterating this object calling the items by index and using .length:

for (var i = 0; i < resuts.length; i++) {
            console.log('id:' + resuts[i].id +  ' | ' + 'Code:' + resuts[i].Code}

Now I want to pull this data from the server so I created an object to handle the properties and have this action method:

public ActionResult GetResults()
{
string json = JsonConvert.SerializeObject(new
        {
            results = new List<Question>()
            {
                new Question { id = 1, Code = "Code A},
                new Question { id = 1, Code = "Code B}
            }
        });

        return Json(new { data = json }, JsonRequestBehavior.AllowGet);
}

I'm calling it with this AJAX:

function GetResultsJSON() {    
        $.ajax({        
            type: 'GET',        
            url: '/Home/GetResults/',
            dataType: 'json',  
            traditional: true,     
            success: function (data) {            
                results = data;
            },        
            error: function (data) {
                alert('Error.');
            }
        })
 };

Now my results object contains:

"{" results ":[{" id ":1," Code ":" Code A "},{" id ":1," Code ":" Code B "}]}"

Now I get JavaScript errors when trying to use the length property or call items by index. From what I have read up on, I think my original hard coded object is just an array, however, I have to work differently with the JSON that's returned from my controller.

Can anyone advise on either returning the array format that I was originally working with or the best way to handle the JSON format as it's returned here? I have tried things like

$.each(data, function(i, obj) {
alert(obj.name);
});

but this returns undefined. Any help would be great.

like image 602
StratMan Avatar asked Dec 08 '22 07:12

StratMan


1 Answers

public JsonResult TestAjax(int leagueId)
    {

         var results = new List<BaseballViewModel>()
        {
            new BaseballViewModel{ DivisionId = 1},
            new BaseballViewModel{ DivisionId = 2}
        }.ToList();

         return Json(results, JsonRequestBehavior.AllowGet);            
    }

$.ajax({
            url: "/Home/TestAjax",
            type: "GET",
            data: { leagueId: 5 },
            success: function (data) {

             // alert(JSON.stringify(data)); show entire object in JSON format
                $.each(data, function (i, obj) {
                    alert(obj.DivisionId);
                });
            }
        });
like image 71
CSharper Avatar answered Dec 11 '22 08:12

CSharper