【发布时间】:2020-07-07 07:02:10
【问题描述】:
PostsList 已在 OnGet 方法中正确填充,并且在 HTML 中正确填充循环。在OnPostDeletePost 方法中,它为空。如何正确绑定列表,以便将其填充到整个模型中??
型号:
public List<Post> PostsList { get; set; }
public async Task OnGet(string userId){
PostsList = await _db.Posts.Include(p => p.ApplicationUser).Where(p => p.ApplicationUserId == userId).OrderByDescending(x => x.DateTime).ToListAsync();
}
public async Task<IActionResult> OnPostDeletePost(int? postId)
{
if(postId == null)
{
return NotFound();
}
var postToDelete = PostsList.FirstOrDefault(p => p.Id == postId);
if(postToDelete == null)
{
return NotFound();
}
_db.Posts.Remove(postToDelete);
await _db.SaveChangesAsync();
return RedirectToPage("Profile", new { userId = ApplicationUser.Id });
}
【问题讨论】:
-
每次有请求时都会创建一个新实例,因此您必须再次调用您的_db.....
标签: c# asp.net-core model-binding razor-pages asp.net-core-3.1