1

I'm trying my hand at Json for the first time and I'm not sure what I'm doing wrong here, but my success callback to ever get called. I've got a dropdown called RIPreset, and it calls the below code on change. I know the on change part is working properly. In the code below my alert("popup1") code gets run, I also have a break point in my code behind and can see that the getPreset method is getting called and passing strings to the result, but nothing inside the function inside my .getJSON call. Ie, alert("popup2") never gets called. I take that to mean that I'm not passing valid data from my JsonResult, but I'm not sure what I'm doing wrong. Any help would be appreciated.

Code Behind

    public JsonResult getPreset(int id)
    {
        RIPreset ripreset = db.RIPresets.Find(id);
        return Json(new { Description = ripreset.Description, LaborHours = ripreset.LaborHours, HourlyRate = ripreset.HourlyRate, Amount = ripreset.Amount });

    }

JQuery/Json

<script type="text/javascript">
$(document).ready(function () {
    $("#RIPreset").change(function () {

        var selection = $("#RIPreset").val();
        alert("popup1");
        $.getJSON('@Url.Action("getPreset")', { id: selection }, function (ripreset) {
            alert("popup2");
            $("#txtDescription").val(ripreset.Description);
            $("#txtHourlyRate").val(ripreset.HourlyRate);
            $("#txtLaborHours").val(ripreset.LaborHours);
            $("#txtAmount").val(ripreset.Amount);
        });
    });
});
</script> 
Josh Blade
  • 981
  • 2
  • 10
  • 24
  • not sure how relevant this is, but if you're having trouble debugging ajax requests I'd recommend using a development console in your browser to debug - such as firebug or the chrome dev tools – Derek Adair Aug 24 '12 at 00:56

2 Answers2

2

GET requests are disabled by default for security reasons, change your action to return

public JsonResult getPreset(int id)
    {
        RIPreset ripreset = db.RIPresets.Find(id);
        return Json(new { Description = ripreset.Description, LaborHours = ripreset.LaborHours, HourlyRate = ripreset.HourlyRate, Amount = ripreset.Amount },
                    JsonRequestBehavior.AllowGet);

    }
StanK
  • 4,750
  • 2
  • 22
  • 46
  • That did the trick! Thanks a bunch. Just a side note, why would you ever pass a JSON object if you didn't want to be able to use it? – Josh Blade Aug 24 '12 at 18:21
  • See the answer [here](http://stackoverflow.com/questions/8464677/why-is-jsonrequestbehavior-needed) – StanK Aug 24 '12 at 23:00
1

just change your action like this:

public JsonResult getPreset(int id)
{
    RIPreset ripreset = db.RIPresets.Find(id);
    return Json(new { Description = ripreset.Description, LaborHours = ripreset.LaborHours, HourlyRate = ripreset.HourlyRate, Amount = ripreset.Amount }, JsonRequestBehavior.AllowGet);
}
Thiago Custodio
  • 17,332
  • 6
  • 45
  • 90