如何将Blazor项目中Index.Razor.cs的IList传递至主Razor页面?
问题描述
我正在用Blazor搭建一个上传/下载站点,项目里有Index.razor和Index.Razor.cs文件,后者包含了依赖UploadFileContext的IndexModel(代码如下):
public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; private readonly UploadFileContext _context; public IndexModel(ILogger<IndexModel> logger, UploadFileContext context) { _logger = logger; _context = context; } public IList<PdfFile> Files { get; set; } public void OnGet() { Files = _context.Files.ToList(); } public async Task<IActionResult> OnPostDownloadAsync(int? id) { var myInv = await _context.Files.FirstOrDefaultAsync(m => m.Id == id); if (myInv == null) { return NotFound(); } if (myInv.Attachment == null) { return Page(); } else { byte[] byteArr = myInv.Attachment; string mimeType = "application/pdf"; return new FileContentResult(byteArr, mimeType) { FileDownloadName = $"{myInv.FileType} {myInv.Number}.pdf" }; } } public async Task<IActionResult> OnPostDeleteAsync(int? id) { var myInv = await _context.Files.FirstOrDefaultAsync(m => m.Id == id); if (myInv == null) { return NotFound(); } if (myInv.Attachment == null) { return Page(); } else { myInv.Attachment = null; _context.Update(myInv); await _context.SaveChangesAsync(); } Files = await _context.Files.ToListAsync(); return Page(); } }
我想在主Razor页面中引用这个IList<PdfFile>,通过foreach循环展示每个文件的名称和文件类型,请问该怎么实现?
实现方案
在Razor Pages中,Index.razor页面可直接访问IndexModel的公共属性Files,通过foreach遍历渲染即可,同时可结合后台的下载、删除接口添加操作按钮。
完整Index.razor代码示例
@page "/" @model IndexModel <h1>文件列表</h1> @if (Model.Files == null || !Model.Files.Any()) { <p>暂无文件</p> } else { <table class="table"> <thead> <tr> <th>文件类型</th> <th>文件名称</th> <th>操作</th> </tr> </thead> <tbody> @foreach (var file in Model.Files) { <tr> <td>@file.FileType</td> <td>@$"{file.FileType} {file.Number}.pdf"</td> <td> <!-- 下载按钮 --> <form method="post" asp-page-handler="Download" asp-route-id="@file.Id"> <button type="submit" class="btn btn-primary">下载</button> </form> <!-- 删除按钮 --> <form method="post" asp-page-handler="Delete" asp-route-id="@file.Id" style="display:inline;"> <button type="submit" class="btn btn-danger">删除</button> </form> </td> </tr> } </tbody> </table> }
关键说明
- 绑定模型:通过
@model IndexModel声明页面关联的模型,即可通过Model.Files访问后台的文件列表。 - 空值防护:先判断
Model.Files是否为空或无数据,避免空引用异常,同时给用户友好提示。 - 遍历渲染:直接遍历
Model.Files,逐个输出文件的FileType和与后台下载逻辑一致的文件名。 - 操作接口调用:用表单提交方式触发后台的
OnPostDownloadAsync和OnPostDeleteAsync方法,通过asp-page-handler指定处理方法名,asp-route-id传递文件ID。
内容的提问来源于stack exchange,提问作者Megan Paterson
相关产品推荐
相关产品推荐

