NRKirby NRKirby - 3 months ago 7
Ajax Question

Why isn't my table partial rendering?

I am trying to use a partial view to build a table in my MVC5 application, here is what I have:

ViewModel

public class ResultsViewModel
{
public Results FirstPartyResults { get; set; }

public Results SecondPartyResults { get; set; }

public Results ThirdPartyResults { get; set; }
}


Index.cshtml

@model App.ViewModels.ResultsViewModel

@{
ViewBag.Title = "Start Election";
}

<div id="partialTable">
@{ Html.RenderPartial("_TablePartial", Model); }
</div>




<script>
$(document)
.ready(function () {
$.ajax({
url: '/Home/StartElection',
type: 'POST',
data: "test",
})
.done(function(partialViewResult) {
$("partialTable").html(partialViewResult);
});
});
</script>


_TablePartial.cshtml

@model App.ViewModels.ResultsViewModel

<div class="page-header">
<h1>Party Results</h1>
</div>

<div id="partialTable">
<table class="table table-striped">
<thead>
<tr>
<th>Party Code</th>
<th>Number of Seats</th>
<th>Overall Share of Votes
</tr>
</thead>
<tbody>
@if (Model != null)
{
<tr>
<td>
@Model.FirstPartyResults.PartyCode
</td>
<td>
@Model.FirstPartyResults.NumberOfSeats
</td>
<td>
@Model.FirstPartyResults.ShareOfVotes
</td>
</tr>
<tr>
<td>
@Model.SecondPartyResults.PartyCode
</td>
<td>
@Model.SecondPartyResults.NumberOfSeats
</td>
<td>
@Model.SecondPartyResults.ShareOfVotes
</td>
</tr>
<tr>
<td>
@Model.ThirdPartyResults.PartyCode
</td>
<td>
@Model.ThirdPartyResults.NumberOfSeats
</td>
<td>
@Model.ThirdPartyResults.ShareOfVotes
</td>
</tr>
}
</tbody>
</table>
</div>


Controller code

[HttpGet]
public ActionResult StartElection()
{
return View();
}

[HttpPost]
public ActionResult StartElection(string text)
{
var scoreBoard = new ScoreBoard();

var viewModel = scoreBoard.GetTopResults();

return PartialView("_TablePartial", viewModel);
}



  • I've set a break point at the controller, the view model object is created as expected

  • I've also set a breakpoint in the partial at the condition checking of the
    Model
    is null & the code within is being executed




The page is being rendered with the table heading but not the model table data - can anyone see what I'm doing wrong?


Note: I am wanting the table to be updated over time through ajax calls - I'm not trying to do that (yet) here but explains why I have a
GET
action result and a
POST

Answer

Since the partial view is inside a div with id partialTable

<div id="partialTable">
    @{ Html.RenderPartial("_TablePartial", Model); }
</div>

Here's where you're wrong

$("partialTable").html(partialViewResult);

You need to use # (jQuery ID Selector) to select the element by its id

$("#partialTable").html(partialViewResult);
Comments