0

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

1 Answer 1

2

Try this:

return Json(jsonTemplates.ToList(), JsonRequestBehavior.AllowGet);
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers, that seemed to work :-) wonder why it didn't work without the Request Behaviour....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.