xoxo_tw
xoxo_tw

Reputation: 269

mvc-4 generate list in view

I have a little problem with getting my View to generate properly.

I get Error: Model does not contain a public definition for 'GetEnumerator'

I have tried to change my generic list into a IEnumerable list but then it popped a few more errors in the code I couldnt get rid of, Im not sure if I have to add it to my UploadedFile class somehow ?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Mvc_fileUploader.Models
{
    public class UploadedFile
    {
        public string Name { get; set; }
        public string Path { get; set; }

        public long Size { get; set; }

    }
}

Controller:

[HttpGet]
        public ActionResult UploadedFiles()
        {
            var uploadedFiles = new List<UploadedFile>();

            var files = Directory.GetFiles(Server.MapPath("~/fileUploads/"));

            foreach (var file in files)
            {
                var fileInfo = new FileInfo(file);

                var uploadedFile = new UploadedFile();

                uploadedFile.Name = Path.GetFileName(file);
                uploadedFile.Size = fileInfo.Length;
                uploadedFile.Path = ("~/fileUploads/") + Path.GetFileName(file);

                uploadedFiles.Add(uploadedFile);
            }

            return View();

View:

@model Mvc_fileUploader.Models.UploadedFile

@{
    ViewBag.Title = "UploadedFiles";
}

<h2>UploadedFiles</h2>

<table style="background-color:lightpink; border:solid 2px black;">
    <tr>
        <td>Name</td>
        <td>Size</td>
        <td>Preview</td>
    </tr>

    @foreach (var file in Model)
    {
        <tr>
            <td>@file.Name</td>
        </tr>       
    }

</table>

the source on github: https://github.com/xoxotw/mvc_fileUploader

Upvotes: 0

Views: 3148

Answers (2)

WestDiscGolf
WestDiscGolf

Reputation: 4108

Need to set the model of the view to be

IEnumerable<Mvc_fileUploader.Models.UploadedFile>

[EDIT]

You're not returning the model. In your controller action; add the list you've created to the View() call, eg:

[HttpGet]
        public ActionResult UploadedFiles()
        {
            var uploadedFiles = new List<UploadedFile>();

            var files = Directory.GetFiles(Server.MapPath("~/fileUploads/"));

            // do stuff

            return View(uploadedFiles);

Upvotes: 3

Atish Kumar Dipongkor
Atish Kumar Dipongkor

Reputation: 10422

@model Mvc_fileUploader.Models.UploadedFile

It is used when only one model is passed to the view. If u want to pass list of model, then u have to write like following.

IEnumerable<Mvc_fileUploader.Models.UploadedFile>

Upvotes: 0

Related Questions