gpt4 book ai didi

c# - 如何使此 var 在 Razor Pages 中可访问

转载 作者:太空宇宙 更新时间:2023-11-03 22:41:18 24 4
gpt4 key购买 nike

我在索引页面后面有以下代码:

public async Task OnGetAsync()
{
var tournamentStats = await _context.TournamentBatchItem
.Where(t => t.Location == "Outdoor" || t.Location == "Indoor")
.GroupBy(t => t.Location)
.Select(t => new { Name = $"{ t.Key } Tournaments", Value = t.Count() })
.ToListAsync();

tournamentStats.Add(new { Name = "Total Tournaments", Value = tournamentStats.Sum(t => t.Value) });
}

同样在这段代码后面我有这个类的定义:

public class TournamentStat
{
public string Name { get; set; }

public int Value { get; set; }
}

public IList<TournamentStat> TournamentStats { get; set; }

如何将 tournamentStats/TournamentStats 引用到 Razor Pages 中?

最佳答案

引用 Introduction to Razor Pages in ASP.NET Core

public class IndexModel : PageModel {
private readonly AppDbContext _context;

public IndexModel(AppDbContext db) {
_context = db;
}

[BindProperty] // Adding this attribute to opt in to model binding.
public IList<TournamentStat> TournamentStats { get; set; }

public async Task<IActionResult> OnGetAsync() {
var tournamentStats = await _context.TournamentBatchItem
.Where(t => t.Location == "Outdoor" || t.Location == "Indoor")
.GroupBy(t => t.Location)
.Select(t => new TournamentStat { Name = $"{ t.Key } Tournaments", Value = t.Count() })
.ToListAsync();

tournamentStats.Add(new TournamentStat {
Name = "Total Tournaments",
Value = tournamentStats.Sum(t => t.Value)
});

TournamentStats = tournamentStats; //setting property here

return Page();
}

//...
}

并访问 View 中的属性

例如

@page
@model MyNamespace.Pages.IndexModel

<!-- ... markup removed for brevity -->

@foreach (var stat in Model.TournamentStats) {
//...access stat properties here
}

关于c# - 如何使此 var 在 Razor Pages 中可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52095002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com