Click here to Skip to main content
15,887,341 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
Hi,

I am trying to get object array from my controller,
i can see that data is returned, but the javascript array (arr) remains empty....

here is a sample of my code, what am i doing wrong?

JS:

JavaScript
var arr = [];
    var onSuccess = function (data) {
            arr = data;
    };

        $.ajax({
            type: 'GET',
            url: 'MyController/GetCurrentAlarms',
            traditional: true,
            success: function (data) { onSuccess(data); },
        });


Controller:

C#
public JsonResult GetCurrentAlarms()
        {
            List<Alarm> list = new List<Alarm>();

            Alarm alm = new Alarm()
            {
                ID = 1,
                Name = "Alarm1"
            };

            list.Add(alm);

            alm = new Alarm()
            {
                ID = 2,
                Name = "Alarm2"
            };

            list.Add(alm);

            alm = new Alarm()
            {
                ID = 3,
                Name = "Alarm3"                
            };

            list.Add(alm);
         
            return Json(list.ToArray(), JsonRequestBehavior.AllowGet);
        }
Posted

1 solution

Try this
JavaScript
var _url = '@Url.Action("GetCurrentAlarms" ,"Home")';
       $.ajax({
           url: _url,
           dataType: "json",
           type: "GET",
           contentType: 'application/json; charset=utf-8',
           success: function (data) {
               onSuccess(data);
           },
           error: function (xhr) {
               debugger;
               alert('error');
           }
       });

   });

   var arr = [];
   var onSuccess = function (data) {
       arr = data;
       alert(arr);
   };
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900