Jon Jon - 4 years ago 136
HTML Question

How to add a list of files to a ViewModel

I have a view that accepts files. The reason for this is so users can upload images. Normally when doing this I would have an input for a file, then post the file back to my controller where I could convert it and use it.

However, in this particular view there are multiple files and an unknown number of files to upload. Therefore, I can't simply post the file back to my controller. My thought was that I would create a ViewModel and in the ViewModel there would be a list of files that would store the added files. Then I would post the ViewModel back and gather the list of files.

My issue is that I don't know how to add the files to my ViewModel after a user uploads them. Normally for text I would use something like an editorfor, but I'm not sure if there is such thing as a fileuploadfor.

I'm assuming I could modify my current method of inputting a file to then assign it to my ViewModel, but I don't know how.

My current method of getting a file:

<input type="file" name="file" />


I would like to add that file to the list Model.InputFiles. Model.InputFiles is a list of type HttpPostedFile

Answer Source

Simply you could make a editor template for HttpPostedFileBase and use it in your view. To do so first in Views\Shared\EditorTemplates folder create a file with name of HttpPostedFileBase.cshtml with following content:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue.ToString(),new{type="file"})

Now consider your view model like this:

public class MyViewModel
{
    public HttpPostedFileBase[] InputFiles { get; set; }
    // other properties 
}

And your action method could be like this:

public ActionResult MyAction()
{
    // a simple example 
    return View(new MyViewModel{ InputFiles = new InputFiles[10] });
}

[HttpPost]
public ActionResult MyAction(MyViewModel model)
{
    var myFile=model.InputFiles[0];
}

At last you could easily use EditorFor() method:

@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    // name your variable same as your collection name to model binder bind it to your collation 
    @foreach (var InputFiles Model.InputFiles)
    {
        @Html.EditorFor(m => InputFiles)
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download