1

I am trying to retrieve a list of objects via jQuery Ajax

I have a controller Method like this:

[HttpGet]
public JsonResult GetAllStates(string listname = "")
{
     clsDdl ddl = new clsDdl();
     List<clsDdl> retval = new List<clsDdl>();
     ddl.id = "1";
     ddl.value = "Dropdown1";
     ddl.status = "DDL Status";
     ddl.attributes = "First Dropdown Text";
     retval.Add(ddl);

     //return retval;
     return Json(new
     {
         list = retval
     }, JsonRequestBehavior.AllowGet);
}

Heres my Dropdown class that I am trying to return

public class clsDdl
{
    public string id { get; set; }
    public string value { get; set; }
    public string status { get; set; }
    public string attributes { get; set; }
}

Code in my view looks like this

 function LoadListItems (options) {

 var listname = options.listname;

$.ajax({
         type: "GET",
         url: url,
         data: JSON.stringify({
             listname: listname
         }),
         contentType: "application/json; charset=utf-8",
         async: true,
         success: function (result) {
            alert(result[0].value);
         },
         error: function (xhr, status, err) {
           alert(err.toString(), 'Error - LoadListItemsHelper');
         }
       });

My controller action is being hit. But the alert is always 'Undefined'. I have also tried

 success: function (data) {
                 var result = data.d;
                 for (var i = 0; i < result.length; i++) {
                 alert(result[i].attributes);
                 }

No Success there either. What am I doing wrong ?

Thanks in advance...

nik0lai
  • 2,585
  • 23
  • 37
w2olves
  • 2,229
  • 10
  • 33
  • 60
  • It looks like you are returning JSON inside a named property called list. What do you get for `alert(data.list);`? – iCollect.it Ltd May 12 '15 at 14:47
  • I added this code success: function (data) { var result = data.list; alert(data.list); alert(result.length); The alert is 'Undefined' the second alert gives the error 'Unable to get property 'length' of undefined or null reference – w2olves May 12 '15 at 14:56
  • When you receive the json in your browser can you analyze the response if it hsa something, if is empty you should start too see why is not returning to the view correctly – Jorge F May 12 '15 at 15:44
  • Thanks for the hint on console and response. Solved my problem – w2olves May 12 '15 at 16:41

1 Answers1

5

1. You are returning JSON from the server. You have to set dataType in Ajax request to json

  1. contentType --> Data sending to server

  2. dataType --> data returned from Server

What is content-type and datatype in an AJAX request?

      $.ajax({
        type: "GET",
        url: url,
        data: JSON.stringify({  listname: listname }),
        contentType: "application/json; charset=utf-8",

//HERE
        dataType: 'json',
        success: function (result) {
              alert(result[0].value);
        },
        error: function (xhr, status, err) {
               alert(err.toString(), 'Error - LoadListItemsHelper');
        }
    });

2.

You are returning

return new Json(new {list = retval}, JsonRequestBehavior.AllowGet);

In success: function(result)

You can access the list like this: result.list[index]

success: function (result) {

      for(var i =0; i < result.list.length; i++){

         alert(result.list[i].value);
         alert(result.list[i].status);
      }
}

EDIT Based on Aivan Monceller 's comments you can do this:

As you are sending GET you don't need the

contentType: "application/json; charset=utf-8",

So you can write you Ajax like this:

      $.ajax({
        type: "GET",
        url: url,
        data: {  listname: listname },

//HERE
        dataType: 'json',
        success: function (result) {
              alert(result[0].value);
        },
        error: function (xhr, status, err) {
               alert(err.toString(), 'Error - LoadListItemsHelper');
        }
    });
Community
  • 1
  • 1
Dawood Awan
  • 7,051
  • 10
  • 56
  • 119
  • I made changes according to your suggestion. Thank you for the link by the way, very helpful. The error I am getting is SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data I am looking into this but if you have a suggestion, please feel free to share... – w2olves May 12 '15 at 15:07
  • What response are you getting from the server? Do console.log(result) in your success function – Dawood Awan May 12 '15 at 15:14
  • 1
    Also you don't have to do this `data: JSON.stringify({ listname: listname })` . You can simply do `data:{ listname: listname }` – Aivan Monceller May 12 '15 at 15:47
  • 1
    having said that I don't think you need this `contentType: "application/json; charset=utf-8"` , since `listname` is a `GET` parameter – Aivan Monceller May 12 '15 at 15:49
  • @AivanMonceller you are correct on both counts. Thanks so much. – w2olves May 12 '15 at 16:40
  • @DawoodAwan thanks for the comprehensive response, it ultimately helped me solve the problem. Thanks again... – w2olves May 12 '15 at 16:42