Richard
Richard

Reputation: 224

DropDownList containing list of files in a directory on Edit and Create views in MVC4 web application

I want to display drop down box containing list of files in a directory on Edit and Create views in MVC4 web application. I have used this in my edit section of the controller:

DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/DownloadFiles"));
var filesListing = directory.GetFiles().ToList<FileInfo>();
ViewBag.zipListing = filesListing;

and this in the edit view:

@Html.DropDownListFor(model => model.DownloadName, new SelectList   (ViewBag.zipListing).AsEnumerable())

Which works fine, (DownloadName is the name of the table field), It updates the field and displays correct db table item on Edit page load. However If I try to use this in the Create view It errors out complaining about Null or cannot find reference.

I have a copy of the block:

DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/DownloadFiles"));
var filesListing = directory.GetFiles().ToList<FileInfo>();
ViewBag.zipListing = filesListing;

in the Create section of the controller with the var filesListing and ViewBag.zipListing renamed to avoid confusion (I guess I should put the dir reading to list stuff in a single place but one thing at a time maybe..)

Any ideas how to use this directory listing as a drop down in the Create view please? I have tried many variations but nothing seems to work. Thanks you for your time.

Upvotes: 0

Views: 2182

Answers (1)

Perry
Perry

Reputation: 611

Rather than using ViewBag, have you thought of just adding a property to the model you are binding to the create view like so:

public List<FileInfo> FileList 
    {
        get
        {
            DirectoryInfo directory = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/DownloadFiles"));
            return directory.GetFiles().ToList<FileInfo>();
        }
    }

Upvotes: 1

Related Questions