开发者

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)
                continue;
            string savedFileName = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                Path.GetFileName(hpf.FileName));
            hpf.SaveAs(savedFileName);

            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:

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

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 foreach loop.


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

IEnumerable<ViewDataUploadFilesResult>

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

View(r);

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜