我正在尝试使用局部视图在我的MVC5应用程序中构建一个表,这就是我所拥有的:
视图模型
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>
控制器代码
[HttpGet]
public ActionResult StartElection()
{
return View();
}
[HttpPost]
public ActionResult StartElection(string text)
{
var scoreBoard = new ScoreBoard();
var viewModel = scoreBoard.GetTopResults();
return PartialView("_TablePartial", viewModel);
}
Model
为null&amp;正在执行的代码页面正在使用表格标题呈现,但不是模型表格数据 - 任何人都可以看到我做错了什么吗?
注意:我希望通过ajax调用随时更新表格 - 我还没有尝试在此处执行此操作,但解释了为什么我有{{1}行动结果和GET
答案 0 :(得分:1)
由于局部视图位于ID为partialTable
<div id="partialTable">
@{ Html.RenderPartial("_TablePartial", Model); }
</div>
这里你错了
$("partialTable").html(partialViewResult);
您需要使用#
(jQuery ID Selector)按ID选择元素
$("#partialTable").html(partialViewResult);