views:

63

answers:

1

Hi,

I'm currently attempting to retrieve a list of objects from my database using jQuery. I have been attempting to use getJSON but the callback is never fired. However, if I use

$.post(url, data, callback)

... then it seems to fire just fine.

My controller actions is thus:

public ActionResult GetTemplates()
{
    IEnumerable<Template> templates = TemplateDAO.GetTemplates();
    List<TemplateViewModel> jsonTemplates = new List<TemplateViewModel>();

    foreach(Template t in templates)
    {
        TemplateViewModel tvm = new TemplateViewModel(t.ID, t.TemplateName);
        jsonTemplates.Add(tvm);
    }

    return Json(jsonTemplates.ToList());

}

and the TemplateViewModel is:

public class TemplateViewModel
{
    public int ID {get; set; }
    public string TemplateName {get; set; }
}

The javascript I'm attempting to use is:

    function LoadTemplates() {
        alert("loading templates");
        var url = '<%= Url.Action("GetTemplates", "Project") %>';

        $.getJSON(url, null, function(data) {
            alert("Succeeded" + data);
        });

    }

This javascript does not show the "Succeeded" alert for some reason, whereas replacing the getJSON call with

$.post(url, null, updateTemplates, 'json');

works.

Any ideas?

It's more of a curiosity thing now that $.post works, but I'd like to know what I'm doing wrong, as every example I've seen looks exactly like mine!

Cheers,

Chris

+2  A: 

Try this:

return Json(jsonTemplates.ToList(), JsonRequestBehavior.AllowGet);
Frozzare
Cheers, that seemed to work :-) wonder why it didn't work without the Request Behaviour....
Chris