Vish
Vish

Reputation: 473

jquery $.get() callback does not process partial view

I'm making an HttpGet request with jquery as follows:

$.get("@Url.Action("PbisForSprint", "SprintBacklog")/" + sprintId, function (result) {
                    oTable.fnOpen(nTr, result, 'details');
                });

oTable.fnOpen is a function defined in Data Tables scripts that adds a row to my data table. The get request should return a list of pbis associated with the selected sprint.

My controller should return a partial view, but if I have that code, nothing is displayed. However, if I return a string, the string is displayed. For example, the following code does not work:

    public ActionResult PbisForSprint(int id)
    {
        //get Sprint
        var sprint = sprintRepository.GetById(id);            
        return View(sprint.Pbis);
    }

but if I change it to

public stringPbisForSprint(int id)
    {
        //get Sprint
        var sprint = sprintRepository.GetById(id);            
        return "This is just test data, I hope I don't need to return html strings";
    }

then my page displays fine.

Here's the view I'm trying to send:

@model IEnumerable<Pbi>

<table cellpadding="4" cellspacing="0" border="0" style="padding-left:50px;">
    <tr>
        <th>Id</th>
        <th>Title</th>
        <th>Story Points</th>
        <th>Level of done</th>
    </tr>
@foreach (var item in Model)
{
    <tr>
        <td>@item.Id</td>
        <td>@item.Title</td>
        <td>@item.StoryPoints</td>
        <td>@item.Done</td>
    </tr>
    <tr>
        <td>
            @Html.ActionLink("Create New", "Create")
        </td>
    </tr>
}
</table>

Thanks in advance for any help anyone is able to offer.

Upvotes: 0

Views: 1638

Answers (1)

RPM1984
RPM1984

Reputation: 73123

Couple of things to try:

  • Don't return a View, return a Partial (i suspect that's what you want anyway):

    return PartialView(sprint.Pbis);

And of course you need to create a partial view, not a full one.

  • Always do incremental coding when dealing with AJAX. Start out with just trying to render out the partial to a DIV on the page as it is. Then once that works, then look at enhancing for your data table stuff.

I'm pretty sure my first point is your problem. You can't have nested <html> elements on a single page. There can only be one <html> element.

Bonus tip (free of charge) - don't tack on QS variables to the URL:

@Url.Action("PbisForSprint", "SprintBacklog")/" + sprintId

Use the second parameter to $.get, which is the data (querystring for GET, form values for POST):

$.get('@Url.Action("PbisForSprint", "SprintBacklog")', { id: sprintId }, function(result)

Upvotes: 1

Related Questions