Search code examples
c#asp.net-mvcasp.net-mvc-4viewbag

How to create view to display list of files in ASP.Net MVC 4 project


I am learning ASP.Net MVC 4 Programming. Currently, I want to display the list of files to the web page. Following is what I did till now.

In the HomeController.cs I edited the Contact action as follows:

public ActionResult Contact()
{
     ViewBag.Message = "Your file page.";
     DirectoryInfo dirInfo = new DirectoryInfo(@"c:\");
     List<string> filenames=dirInfo.GetFiles().Select(i=>i.Name).ToList();
     ViewBag.data = filenames; 
     ///^^ Is this correct??    

     return View();
}

I want the filenames to be displayed to the web page. What should I write in my view? I right clicked the Contact action and got the default view, containing:

@{
    ViewBag.Title = "Contact";
}

<h2>Contact</h2>

Solution

  • As @ChrisV wrote, you may want to create a strongly typed view. That means that you're associating a Model with your View. You would then pass the data using the View() overload which takes the Model as parameter. In your current version, you're sending data to the view using the ViewBag. That's not wrong, but it would be probably best to create a strongly typed view, at least as you go along learning.

    That being said, I would probably do the following changes:

    In your controller, get a list of FileInfo objects, instead of file names. The FileInfo type exposes additional features that you can use to enrich the displayed data.

    public ActionResult Contact()
    {
        ViewBag.Message = "Your file page.";
        DirectoryInfo dirInfo = new DirectoryInfo(@"c:\");
        List<FileInfo> files = dirInfo.GetFiles().ToList();
    
        //pass the data trough the "View" method
        return View(files);
    }
    

    Next, you need to specify the model type inside your view, and to iterate and display the data:

    @model IEnumerable<FileInfo>
    
    @{
         ViewBag.Title = "Contact";
    }
    
    <h2>Contact</h2>
    
    <ul>
    @foreach (FileInfo file in Model)
    {
         <li>@file.Name</li>
    }
    </ul>
    

    Please note, what and how you actually display on the page is up to you. You could create a table for the files and display the creation time, the size or even a command (download, delete, etc.). This is just a "template"; use it as such.