Aaron Patten Aaron Patten - 11 months ago 92
ASP.NET (C#) Question

File upload error using foreach loop. "...does not contain a public definition for 'GetEnumerator'"

I am trying to get a file uploader to work. I am following the tutorial "A Back To Basics Case Study: Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks", but I am not using TDD because I am pressed for time and also I am relatively new to ASP.NET MVC.

When I use the example code provided (with minor modifications to adjust for the difference in context) I get the following error at runtine:

Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'AnswerApp.Models.ViewDataUploadFilesResult' because 'AnswerApp.Models.ViewDataUploadFilesResult' does not contain a public definition for 'GetEnumerator'

There have been suggestions about using casts and declaring the variable var as IEnumerable, but none have worked for me. I have spent several days researching the problem and have even tried to write my own enumerator, but the compiler doesn't see my GetEnumerator function even in that case.

In my controller:

public ActionResult ViewAnswer(ViewDataUploadFilesResult model)
List<ViewDataUploadFilesResult> r = new List<ViewDataUploadFilesResult>();

foreach (string file in Request.Files)
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
string savedFileName = Path.Combine(

r.Add(new ViewDataUploadFilesResult()
Name = savedFileName,
Length = hpf.ContentLength
return View(model);

In my model:

public class ViewDataUploadFilesResult
public string Name { get; set; }
public int Length { get; set; }

In my view:

<% foreach (AnswerApp.Models.ViewDataUploadFilesResult v in this.ViewData.Model) { %>
<%=String.Format("<li>Uploaded: {0} totalling {1} bytes.</li>",v.Name,v.Length) %>
<% } %>

Should I create my own Enumerator? If so, how do I go about doing that. Also, how do I make it recognizeable to the foreach loop (currently creating the GetEnumerator method still causes the sam error; therefore, even when it does exist is is invisible to the

Answer Source

You need your view to bind to an IEnumerable of ViewDataUploadFilesResult instead of a ViewDataUploadFilesResult:


Then in your action you call View on the list instead of on one result:


And your ViewAnswer action shouldn't take in any parameters unless you want people to pass in parameters to your routine.