Search code examples
c#asp.netblazorrazor-pagesblazor-webassembly

Passing List from .razor.cs file to the main razor page


I am creating an upload/download site with blazor, and in my project. I have an index.razor file and an Index.Razor.cs file where I am putting my Index model which references the dbcontext etc. (see code below)

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

I am trying to reference my ilist in the main razor page which I will use in a foreach loop, to display the name and filetype of each file.

How can I do this?


Solution

  • You can define foreach loop with Files in Razor page.

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