0

I don't think my question is unique but I will ask as there might be some peculiarities with regards to my question. I have a Business Model that loads files from a folder with and displays them on a webpage for editing and other desired operations. My controller calls on this model like so: This is the method that handles the listing of files and returns an enumeration of fileinfo objects

    public IEnumerable<FileInfo> ListUploadedFiles(HttpContextBase htc)
    {
        //list all the files from the upload directory
        var path = htc.Server.MapPath("~/FileUpload");
        var di = new DirectoryInfo(path);
        return di.EnumerateFiles();
    }

This is the code in the controller action that should populate a viewmodel and pass the viewmodel a view which is where I am having a bit of an issue.

            var viewmodel = new List<UploadedImageViewModel>();

        var files = uploader.ListUploadedFiles(context);

        foreach (var item in files)
        {
            viewmodel.Add(new UploadedImageViewModel()
            {
                ImageName = item.Name,
                CreatedOn = item.CreationTime,
                ImageSize = item.Length,
                FileType = item.Extension
            });
        }

        return View("ListFiles", viewmodel);

Now in my view I do this to list out the desired properties on the view:

@using SeeSite.Models
@model IEnumerable<UploadedImageViewModel>

@{
    ViewBag.Title = "Upload";
}
@foreach(UploadedImageViewModel items in Model)
{
  <li>@items.ImageName <span><a href="#details">Details</a></span>
  <span><a href="#rename">Rename</a></span>
  </li>
}

but I keep getting an exception:

System.NullReferenceException: Object reference not set to an instance of an object.

And points to the line where my foreach begins. Now just to clear things up, if I use ViewBag it works fine though I can only access the details of one file, but using a viewmodel just doesn't work. Been stuck here for a whole day and don't want to waste anymore time. What could be wrong?!

Oh and if I do this in the view:

@foreach (var dir in new DirectoryInfo(Server.MapPath("~/FileUpload"))
              .EnumerateFiles())
{
     <li>@dir.Name <span>|</span><a href="#">Details</a> 
     <span>|</span> <a href="#">Rename</a></li>
}

it works. So am I missing something here or is this the best solution to do what I am trying to do?

Saagar Elias Jacky
  • 2,684
  • 2
  • 14
  • 28
Joseph Izang
  • 766
  • 1
  • 13
  • 43

0 Answers0