parabellum27
parabellum27

Reputation: 9

Displaying data from ViewBag into table?

I'm trying to retrieve a list of file info for .dll files from a specific directory to display on a ASP.NET webpage. The info I want displayed is the file name, the date it was last modified and the version.

So far I have the data being stored in a ViewBag and being displayed in the view, however it's messy and I want it to be displayed in a table.

Is there a way to take data from a ViewBag and place it in a table or is there better way than using the ViewBag?

This is the code I have for the View so far:

@using System.Diagnostics

@{
    ViewBag.Title = "Versions";
}
<h2>Versions</h2></br>

<h3>File Name       Last Modified        Version</h3>

@ViewBag.FileList

@for(int i =0; i < ViewBag.FileList.Length;i++)
{
    <p>
    @ViewBag.FileList[i];
    @{ FileInfo f = new FileInfo(ViewBag.FileList[i]);

   <table>
  <td><tr>@f.Name</tr></td> 
  <td><tr> @f.LastAccessTime</tr></td>

 </table>
      FileVersionInfo currentVersion = FileVersionInfo.GetVersionInfo(ViewBag.FileList[i]);
      @currentVersion.FileVersion


        }

   </p>
}

Upvotes: 0

Views: 11176

Answers (1)

DanKodi
DanKodi

Reputation: 3640

ViewBag should not be exploited this way. Use a View Model

In your controller's action pass the data like this,

public ActionResult Files()
        {
            List<FileInfo> fileNames = ...get file names
            return View(fileNames);
        }

In your view, Right at the top, define the type of object

@model IEnumerable<System.IO.FileInfo>

Your table should be layed out in a way similar to the below.

<table>
    <tbody>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.LastAccessTime</td>
        </tr>
    }
    </tbody>
</table>

Upvotes: 3

Related Questions