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

时间:2018-08-30 10:40:39

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

对于索引页面,我后面有以下代码:

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中?

1 个答案:

答案 0 :(得分:3)

引用Introduction to Razor Pages in ASP.NET Core

String a = "Peter";
List<String> list = ...
list.add(a);
a = null;

并在视图中访问属性

例如

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

    //...
}
相关问题