【问题标题】:How to make this var accessible in Razor Pages如何使此 var 在 Razor 页面中可访问
【发布时间】:2018-08-30 10:40:39
【问题描述】:

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

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 页面?

【问题讨论】:

    标签: c# asp.net-core razor-pages


    【解决方案1】:

    参考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();
        }
    
        //...
    }
    

    并访问视图中的属性

    例如

    @page
    @model MyNamespace.Pages.IndexModel
    
    <!-- ... markup removed for brevity -->
    
    @foreach (var stat in Model.TournamentStats) {
        //...access stat properties here
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2020-12-12
      • 2019-12-23
      • 2018-10-31
      • 2011-06-23
      • 2020-09-02
      • 2020-05-26
      • 2020-05-01
      • 2018-08-20
      相关资源
      最近更新 更多