views:

887

answers:

5

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.

A: 

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>");
 });
Mike Blandford
A: 

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.

Richard
A: 

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.

James
A: 

im having the same problem!!

when opend in Firebug it seems the response is appended to script tag created.. but its all raw.. and the callback function never fired

this is what i see in Firebug.. Untitled Document

1{"type":"FeatureCollection","features":[{"type":"Feature","id":"states.1","geometry":{"type":"MultiPolygon","coordinates":[[[[37.51099000000001,-..............]}

as u can see the url has been set as source.. and received data has been appended.. but the callback function never got called

Imran
+3  A: 

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);
}
Nexxas