I can’t seem to unpack a string list from a JSONResult.
Here is the controller:
[HttpPost]
public JsonResult GetDescriptions(string incomingProjectName)
{
List<string> result = new List<string>();
using (SFEntities ctx = new SFEntities())
{
result = (from ct in ctx.SF_CLIENT_TASK
join cp in ctx.SF_CLIENT_PROJECT on ct.PROJECT equals cp.ID
where cp.NAMEX == incomingProjectName
select ct.DESCRIPTION).ToList();
}
return Json( result );
}
And here is my ajax method:
$.ajax({
type: "POST",
url: "Home/GetDescriptions",
contentType: "application/json; charset=utf-8",
data: '{incomingProjectName : "projName"}',
dataType: "json",
success: function (msg) {
alert("msg: " + msg); // [Object object]
alert("msg: 2 string: " + msg.toString); // function toString() { [native code] }
var list = eval(msg);
alert("list: " + list); // blank
alert("list to string: " + list.toString); // function toString() { [native code] }
alert("list data: " + list.valueOf); // valueOf() { [native code] }
alert("msg[0]: " + msg[0]); // undefined
alert("list[0]: " + list[0]); // undefined
},
});
In the debugger I can see the contents of result has a long list of items, but I don’t seem them however I try to access it in the JavaScript.
Is there some kind of de-serialize or extract method I’m failing to call?
EDIT: This seems like it should be a boilerplate thing, but I haven’t been able to google many examples of doing this for some reason …
EDIT: Here is my final (working) code:
$.ajax({
type: "POST",
url: "Home/GetDescriptions",
data: { incomingProjectName: projName },
success: function (msg) {
alert( "msg: " + msg );
},
error: function (msg) {
alert("Failed: " + msg.status + ": " + msg.statusText);
}
And here is the controller code:
public JsonResult GetDescriptions(string incomingProjectName)
{
List<string> result = new List<string>();
using (SFEntities ctx = new SFEntities())
{
result = (from ct in ctx.SF_CLIENT_TASK
join cp in ctx.SF_CLIENT_PROJECT on ct.PROJECT equals cp.ID
where cp.NAMEX == incomingProjectName
select ct.DESCRIPTION).ToList();
}
return Json( result );
}
I’ve tested your code with the following controller method and it worked without any problems.
And the JS code:
And the result of the success method:
I believe the problem is that your list is empty or there is a problem with the serializer. Try to see the Json results contents on debug mode.
Update:
To see the data returning from your controller action, please remove the
[HttpPost]attribute and change your return statement toreturn Json( result ,JsonRequestBehavior.AllowGet);on your code Then go tohttp://yoursite/controllername/GetDescriptions?incomingProjectName=projNameto see the returning json.