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...

4
  • It looks like you are returning JSON inside a named property called list. What do you get for alert(data.list);? Commented May 12, 2015 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 Commented May 12, 2015 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 Commented May 12, 2015 at 15:44
  • Thanks for the hint on console and response. Solved my problem Commented May 12, 2015 at 16:41

1 Answer 1

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');
        }
    });
Sign up to request clarification or add additional context in comments.

6 Comments

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...
What response are you getting from the server? Do console.log(result) in your success function
Also you don't have to do this data: JSON.stringify({ listname: listname }) . You can simply do data:{ listname: listname }
having said that I don't think you need this contentType: "application/json; charset=utf-8" , since listname is a GET parameter
@AivanMonceller you are correct on both counts. Thanks so much.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.