我正在尝试使用部分 View 在我的 MVC5 应用程序中构建一个表,这是我所拥有的:
View 模型
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 代码
[HttpGet]
public ActionResult StartElection()
{
return View();
}
[HttpPost]
public ActionResult StartElection(string text)
{
var scoreBoard = new ScoreBoard();
var viewModel = scoreBoard.GetTopResults();
return PartialView("_TablePartial", viewModel);
}
- 我在 Controller 上设置了一个断点, View 模型对象已按预期创建
- 我还在
Model
的条件检查为 null 且其中的代码正在执行时在部分中设置了断点
The page is being rendered with the table heading but not the model table data - can anyone see what I'm doing wrong?
注意:我希望通过 ajax 调用随着时间的推移更新表格 - 我还不想在这里这样做,但解释了为什么我有一个 GET
操作结果和 POST
最佳答案
由于部分 View 位于 ID 为 partialTable
的 div 内
<div id="partialTable">
@{ Html.RenderPartial("_TablePartial", Model); }
</div>
这就是你错的地方
$("partialTable").html(partialViewResult);
您需要使用 #
( jQuery ID Selector ) 通过 id 选择元素
$("#partialTable").html(partialViewResult);
关于javascript - 为什么我的表格没有部分呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38940165/