views:

113

answers:

3

I'm trying to get a json serialized object from within an MVC user control using jQuery. The problem is the result coming back is the full HTML for the page that contains my control. The page and the control use the same controller. I've tried breaking on the method I'm calling in the controller and it never gets hit. I've tried various incarnations of the jQuery Ajax calls, and get the same result.

jQuery code:

<script type="text/javascript">
$('#Project_GeneralContractor_Id').change(function() {
    //alert('<%= Url.Action("GetGeneralContractor", "Projects") %>/1');
    $.get('<%= Url.Action("GetGeneralContractor", "Projects") %>', { id: $('#Project_GeneralContractor_Id').val() }, function(data) {
        alert(data);
    });
});
</script>

Controller code:

public JsonResult GetGeneralContractor(int id)
{
    return Json(_GeneralContractorRepository.Get(id));
}

Where $('#Project_GeneralContractor_Id') is a drop down list and _GeneralContractorRepository.Get(id) returns an individual GeneralContractor object.

Not sure what I have going on, but I suspect the jQuery side since I can't seem to get a break in the controller.

A: 

You need to specify type: json (fourth optional paramter to $.get). See the $.get arguments.

 $.get('<%= Url.Action("GetGeneralContractor", "Projects") %>', { id: $('#Project_GeneralContractor_Id').val() }, function(data) {
        alert(data);
    }, "json");
karim79
I had already tried that. Same result.
mannish
@mannish - Did you try it as above, after the callback?
karim79
Yup, exactly like that.
mannish
@mannish - It's probably your server code that's hiccuping, as Mike already suspected.
karim79
A: 

Have you tried using getJSON()?

If that's not, I'm gonna lean towards server side issue. Hard to guess without looking at the page being returned though.

Mike Robinson
getJSON returns the same thing. Odd thing to note, I just realized that the call is hitting my Index action in that controller. Starting to think it's a route issue.
mannish
I answered my own question on this one, but since you hinted at a server side problem (which it was), you deserve the credit.
mannish
A: 

It was a routing issue. My Projects controller has some special route cases. I created a separate controller to manage GeneralContractors and all is well.

mannish