-2

Model

public class AlldataPoints
{
    public string name {get;set;}
    public string phone {get;set;}
    public string phase {get;set;}
}

Controller

public ActionResult GetResults1()
{
    List<AlldataPoints> lst = (List<AlldataPoints>)Session["list"];
    return Json(new { data = lst }, JsonRequestBehavior.AllowGet);
}

Script

function Pie() {
    $.get("GetResults1", function (abc) {
        var bac = abc;
        for (i = 0; i < bac.length; i++) {
            var hello = bac[0].phase;
        }
    });
} 

As my list has 3 array objects, I want to access the value for phase of each object array and put it into variable hello but on running, hello is undefined.

ManoDestra
  • 6,325
  • 6
  • 26
  • 50
Himaan Singh
  • 725
  • 1
  • 7
  • 17
  • 1
    you are returning a JSON string but you're not parsing it in javascript, hence you are trying to access some properties of a string,. you should instead parse the result using something like: `var bac = JSON.parse(abc);`. Also, keep in mind that an object will be parsed, you may first want to check if you are getting the results first (by doing console.log(abc); and, then, by doing the rest. – briosheje Jul 08 '16 at 12:38
  • the data is getting stored in bac – Himaan Singh Jul 08 '16 at 12:43
  • I know, but you have to think about **what data** is being stored in bac. It's currently a string, and you need to convert it to an object first if you want to iterate through it and get its properties. – briosheje Jul 08 '16 at 12:44
  • data is stores as array[n] – Himaan Singh Jul 08 '16 at 12:46
  • each index is shown as object – Himaan Singh Jul 08 '16 at 12:47
  • Can you tell us what `console.log(abc)` outputs? – evolutionxbox Jul 08 '16 at 12:57

1 Answers1

2

As briosheje mentionned in his comment, the problem may be in the data type. You controller returns a JSON String, and is directly used in your controller. You need to be sure that the data that your Javascript gets is some JSON.

You can use, as suggested, the JSON.parse(yourstring) function, which will make sure that you are actually iterating over a JSON object. What is going on here is the following process:

  • Your controller sends the Json String to your JavaScript.
  • Your JavaScript gets the string in your http request : $.get("GetResults1", function (abc)
  • It then passes the string to bac : var bac = abc
  • You then try to iterate over a string : for (i = 0; i < bac.length; i++)
  • You check for the value at index 0 of your bac variable (which is a String). As JavaScript is a non-typed language, it obeys and considers your variable as an array of characters. So, it checks for your first character.
  • Then, it tries to access the phase field of your character, which does not exist (undefined) and stores it into hello : var hello = bac[0].phase (= undefined).

EDIT You may check as this SO question, which covers your problem very well.

Community
  • 1
  • 1
Yassine Badache
  • 1,810
  • 1
  • 19
  • 38