以下答案的源代码
设置您将使用 AJAX 获取的调用(而不是IEnumerable<T>
使用 a PartialViewResult
(因为您已经定义了_*Partial.cshtml
:
//
// GET: /Desktop/GetPersons
public PartialViewResult GetPersons()
{
var persons = this.desktopService.GetPersons()
.OrderBy(x => Guid.NewGuid()); // randomize to make it look like a refresh
return PartialView("_PeoplePartial", persons);
}
//
// GET: /Desktop/GetPlaces
public PartialViewResult GetPlaces()
{
var places = this.desktopService.GetPlaces()
.OrderBy(x => Guid.NewGuid()); // randomize to make it look like a refresh
return PartialView("_PlacesPartial", places);
}
(对不起,desktopService
这只是获取数据的通用方式)
接下来,添加一个刷新按钮和一些 jQuery 代码来动态获取这些值:
按钮和内容:
<div class="row">
<div class="col-md-3">
<!-- we add "get-persons" class so we can bidn to it with jQuery -->
<button class="btn bt-default pull-right get-persons" data-loading-text="Loading...">Refresh People</button>
</div>
<!-- we also add the "persons" class so we have a target to place
the new content into -->
<div class="col-md-3 text-center persons">
@{ Html.RenderPartial("_PeoplePartial", Model.People); }
</div>
<!-- same things as above, just in referse order: "places" and "get-places" -->
<div class="col-md-3 text-center places">
@{ Html.RenderPartial("_PlacesPartial", Model.Places); }
</div>
<div class="col-md-3">
<button class="btn bt-default get-places" data-loading-text="Loading...">Refresh Places</button>
</div>
</div>
阿贾克斯:
<script>
$(function () {
$(document).on('click', '.get-persons', function (e) {
var $btn = $(this).prop('disabled', !0);
$.ajax('@Url.Action("GetPersons", "Desktop")').done(function (html) {
$('.persons').html(html);
}).always(function(){
$btn.prop('disabled', !1);
});
e.preventDefault();
}).on('click', '.get-places', function (e) {
var $btn = $(this).prop('disabled', !0);
$.ajax('@Url.Action("GetPlaces", "Desktop")').done(function (html) {
$('.places').html(html);
}).always(function () {
$btn.prop('disabled', !1);
});
e.preventDefault();
});
});
</script>