Search code examples
c#asp.net-mvcrazorhtml-helper

Display Each Element From Array Using HTML Helper in C#


This is probably a very simple problem, but I am extremely new to C# / MVC and I have been handed a broken project to fix. So it's time to sink or swim!

I have an array of strings that is being passed from a function to the front end. The array looks something like

reports = Directory.GetFiles(@"~\Reports\");

On the front end, I would like it to display each report, but I am not sure how to do that. This project is using a MVC, and I believe the view is called "Razor View"? I know that it's using an HTML helper.

In essence, I need something like

@HTML.DisplayTextFor(Model.report [And then print every report in the array]);

I hope that makes sense.


Solution

  • If you want to display the file name array you can simply use a foreach:

    @foreach(var report in Model.Reports){ @report }
    

    Note that you should add the Reports property to your view model:

    public class SampleViewModel
    {   
        public string [] Reports { get; set; }
    }
    

    You could use ViewData or TempData but I find that using the view model is the better way.

    You can then populate it:

    [HttpGet]
    public ActionResult Index()
    {
        var model = new SampleViewModel(){ Reports = Directory.GetFiles(@"~\Reports\")};
            
        return View(model);
    }
    

    And use it in the view as you see fit.

    Here is a simple online example: https://dotnetfiddle.net/5WmX5M

    If you'd like to add a null check at the view level you can:

    @if(Model.Reports != null)
    {   
        foreach(var report in Model.Reports){  @report <br> }
    }
    else
    {
        <span> No files found </span>
    }
    

    https://dotnetfiddle.net/melMLW

    This is never a bad idea, although in this case GetFiles will return an empty list if no files can be found, and I assume a possible IOException is being handled.