Reputation: 6509
I'm learning asp.net mvc by working on a test project including SubSonic and jQuery.
The problem that I'm encountering is that every time I want to return something more than a simple string, like a Json object, I get stymied because callbacks don't seem to fire, or come back as failed.
My method to get a list of jobs in the database:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetAllJobs()
{
var db = new JamesTestDB();
var jobs = from job in db.Jobs
select job;
return Json(jobs.ToList());
}
And my JavaScript to call it:
function updateJobList() {
var url = '<%= Url.Action("GetAllJobs", "Home") %>';
$.getJSON(url, null, function(data, status) { alert("Success!"); });
}
I've played around with get, post and getJSON using both inline and outside function definitions for success and failure. Nothing seems to work, but the code is definitely making the Ajax call, just not firing the callback.
Upvotes: 6
Views: 8316
Reputation: 893
Here is the solution!!
So it turns out I had been doing the the exact same way for over a year:
public JsonResult SaveData(string userID, string content)
{
var result = new { Message = "Success!!" };
return Json(result);
}
So, I started to do it the same way on a new project I started up. Well, the difference? The first one was MVC 1.0, and my new one is MVC 2.0. So what's the difference? You have to allow JSON GET requests:
public JsonResult SaveData(string userID, string content)
{
var result = new { Message = "Success!!" };
return Json(result, JsonRequestBehavior.AllowGet);
}
Upvotes: 12
Reputation: 6509
The problem lies somewhere in what I'm returning. It seems that pushing anonymous types into Json() seems to cause it to mess up somehow. By defining a simple class and pushing values into a new instance of it, I got it to return correctly.
Upvotes: 0
Reputation: 22036
Have you tried:
$.getJSON(url, function(data, status) { alert("Success!"); });
and also, check the URL is resolving correctly by doing:
alert(url);
before the call to check it's correct.
Then check the response on the console window of Firebug in Firefox.
Upvotes: 0
Reputation: 4012
jQuery has an error handler that you have to bind if you want to see errors:
$("#msg").ajaxError(function(event, request, settings){
$(this).append("<li>Error requesting page " + settings.url + "</li>");
});
Upvotes: 0