【发布时间】:2021-07-20 12:18:18
【问题描述】:
我有一个 Razor Pages .Net Core 应用程序,我在其中对一个方法进行 ajax 回调,以便检索更多记录以显示在屏幕上:
public async Task<IActionResult> OnGetTimelineEntries(int pageIndex, int pageSize)
{
//System.Threading.Thread.Sleep(4000);
ApplicationUser currentAppUser = await _userManager.GetUserAsync(User);
PopulateUsersEntries(currentAppUser);
GetHookUps(currentAppUser);
foreach (ApplicationUser appUser in AppUsersList)
{
PopulateUsersEntries(appUser);
}
// The above code just populates the below Entries list:
var pagedEntries = Entries
.Skip(pageIndex * pageSize)
.Take(pageSize);
return new JsonResult(pagedEntries.Select(a => new
{
Comment = a.Comment,
thumbNailImage = a.Trip.Season.AppUser.ApplicationUserImage.ImageDataThumb,
IsEstimatedWeight = a.IsEstimatedWeight,
tripTitle = a.Trip.Title,
entryImagesCount = a.EntryImages.Count,
tripSeasonTitle = a.Trip.Season.Title,
appUserFirstName = a.Trip.Season.AppUser.FirstName,
appUserLastName = a.Trip.Season.AppUser.LastName,
entryTime = a.EntryTime.ToShortTimeString() + " - " + a.EntryTime.ToString("dd MMM yyyy"),
isCatch = a.IsCatch,
entryId = a.ID,
imagesCount = a.EntryImages.Count,
firstEntryImage = a.EntryImages.FirstOrDefault(),
fishSpeciesDescription = a.FishSpecies.Description,
fishWeightDescription = a.Weight + " " + a.WeightUnit.Description,
entryImages = a.EntryImages
}));
//return new JsonResult(pagedEntries);
//return new JsonResult(pagedEntries.Select(a => new { results = a }));
}
如您所见,它返回一个 JSON 对象,我必须从该对象中选择我想要的字段,以将它们传递回一个“平面”JSON 对象。如果我尝试通过 JSON (return new JsonResult(pagedEntries);) 将整个 pagedEntries 对象传回,我会在 AJAX 结果中收到错误(根本没有太多信息可以诊断)。
$.ajax({
url: '?handler=TimelineEntries',
beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val()); },
data: { "pageindex": pageIndex, "pagesize": pageSize },
type: "GET",
success: function (data) {
debugger;
if (data != null) {
for (var i = 0; i < data.length; i++) {
$("#container").append("<h2>" +
data[i].comment +
"</h2 > "
);
}
pageIndex++;
}
},
beforeSend: function () {
$("#progress").show();
},
complete: function () {
$("#progress").hide();
},
error: function (e) {
debugger;
alert("Error while retrieving data!");
}
});
有没有更好的方法可以将对象 pagedEntries 传递回部分视图 AJAX 调用,其所有子对象都完好无损,因此我不必将结果展平为一维 JSON 对象?
【问题讨论】:
标签: json asp.net-core .net-core razor-pages