1

I am using jQuery to consume my action.

 $.ajax({   url: '',
            data: 'json',
            type: 'post',
            dataType: options.dataType,
            async: false,
            success: function (obj) { returnValue = obj; }
        });

now....

if I return this one...

var test1 = Json(new { Message = "Any message here.", Status="True" });

the return on my Ajax call is JUST fine..

BUT.. if i return this one(List of users from EF)

var test2 = Json(IoC.Resolve<IUserService>().GetUsers());

I will get undefined/500 (Internal Server Error).

Now the question is how to properly return a JSON from an object so that jQuery ajax can read it properly?

Thanks

Lee
  • 768
  • 1
  • 11
  • 29
  • I had the same problem and is because the list is to long to be passed throw – jcvegan Feb 14 '12 at 16:21
  • Could be a duplicate of this: http://stackoverflow.com/questions/3113952/asp-net-mvc-jsonresult-return-500 – Linus Thiel Feb 14 '12 at 16:22
  • 1
    What is IoC.Resolve().GetUsers() actually returning? Since you are using var I cannot tell what datatype is being returned that you are trying to convert to JSON. – Kevin Junghans Feb 14 '12 at 16:23

2 Answers2

1

Lee,

Have never seen the usage:

var test2 = Json(IoC.Resolve<IUserService>().GetUsers());

before and am not going to comment. However, you MAY get away with merely adding a .ToList() to the end of the statament, i.e.:

var test2 = Json(IoC.Resolve<IUserService>().GetUsers().ToList());

The reason for the issue is due to the fact that you haven't yet enumerated the object out before attempting to populate the json object, therefore you experience all sorts of latency and object reference problems. By adding ToList() you mitigate these problems as the object is fully enumerated before it hits the Json() method.

it might just work, ... or blow right up :)

jim tollan
  • 22,305
  • 4
  • 49
  • 63
0
public ActionResult MethodName(){
var returnList = IoC.Resolve<IUserService>().GetUsers().ToList();
retun JSON(returnList,JSONRequestBehaviour.AllowGet);
}

jQuery Function

success: function (obj) {
alert(obj.d.ListProperty);
// you can access all the properties you have in the list.
}
HaBo
  • 13,999
  • 36
  • 114
  • 206