Reputation: 23
I have been able to post multiple files to my controller successfully by follwing the following:
http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/
However, I am trying to also include some information with each file uploaded that the user must enter e.g A title and version
Here is a demo to maybe show what I am trying to achieve.
Here is what I have currently come up with for dealing with it in this way.
This doesn't seem like the correct way as I am used to passing models to the controller? Another issue with this is if the user adds three file uploads but only selects 2 files, then it will be out of sync.
I have done a bit of searching and couldn't seem to find an example of this.
Upvotes: 2
Views: 3005
Reputation: 183
First create 2 ViewModels
public class NewViewModel
{
// list of files with additional data
public List<UploadItem> UploadItems { get; set; }
public string AnotherPropForView { get; set; }
}
public class UploadItem
{
// your additional data
public string CustomProp1 { get; set; }
public string CustomProp2 { get; set; }
// file
public HttpPostedFileBase UpFile { get; set; }
}
Create controller. One action for display empty form and second for process data from view.
public class SomeController : Controller
{
public ActionResult Create()
{
NewViewModel model = new NewViewModel
{
// inicialize list
UploadItems = new List<UploadItems>
{
// inicialize empty objects ( if you want to have 2 file fields with additional data)
// or inicialize only one object and another fields add by Javascript
new UploadItem {},
new UploadItem {},
}
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(NewViewModel model)
{
// if (ModelState.IsValid) etc...
foreach (var uploadItem in model.UploadItems)
{
// work with file and additional data
var file = uploadItem.UpFile;
var prop1 = uploadItem.CustomProp1;
// file.SaveAs("/some/where"); atc ...
}
// return some view...
}
}
And create view
@model Path.To.NewViewModel
@using (Html.BeginForm("Create", "Some", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@* Print all inicialized upload items *@
@for (int i = 0; i < Model.UploadItems.Count; i++)
{
@Html.TextBoxFor(model => model.UploadItems[@i].CustomProp1)
@Html.TextBoxFor(model => model.UploadItems[@i].CustomProp2)
<input type="file" id="UploadItems[@i].UpFile" name="UploadItems[@i].UpFile" />
}
<button name="Action" type="submit" value="Save" class="btn">Save</button>
}
You can use Javascript for dynamic adding Uploaditem to form - you have to generate right index to name and ID property in inputs
Upvotes: 3