繁体   English   中英

ASP.net 核心 3.1 列表填充在 onGet 中,但不在 OnPost 中。 绑定它的正确方法是什么?

[英]ASP.net core 3.1 List is populated in the onGet but not in OnPost. What is the correct way to bind it?

PostsListOnGet方法中得到正确填充,并且在 HTML 中正确填充循环。 OnPostDeletePost方法中,它为 null。 如何正确绑定列表,使其填充到整个模型中?

模型:

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 });
}

每个请求都是页面模型的一个新实例。 您可以告诉 MVC 从表单值绑定列表;

[BindProperty]
public List<Post> PostsList { get; set; }

但我假设您的意思是从数据库重新加载? 请注意,您可以只加载要删除的记录;

var post = await _db.Posts.Where(p => p.Id == postId).SingleOrDefaultAsync()
...
_db.Posts.Remove(post);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM