【问题标题】:Passing List from .razor.cs file to the main razor page将列表从 .razor.cs 文件传递​​到剃须刀主页面
【发布时间】:2022-10-13 16:06:16
【问题描述】:

我正在使用 blazor 创建一个上传/下载站点,在我的项目中,我有一个 index.razor 文件和一个 Index.Razor.cs 文件,我在其中放置了引用 dbcontext 等的索引模型(请参见下面的代码)

`公共类IndexModel:PageModel { 私有只读 ILogger _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();
    }
}`

我试图在我将在 foreach 循环中使用的剃须刀主页面中引用我的 ilist,以显示每个文件的名称和文件类型。

有人可以建议如何做到这一点吗?

我是 blazor 的新手,所以请放轻松:)

【问题讨论】:

    标签: c# asp.net blazor razor-pages blazor-webassembly


    【解决方案1】:

    您可以在 Razor 页面中使用 Files 定义 foreach 循环。

     <ol>
     @foreach (var file in Files)
     {      
        <li>@file.Name</li>
        <li>@file.FileType</li>          
     }
     </ol>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 2018-05-30
      • 1970-01-01
      • 2021-12-29
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多