I am using jQuery.filer on a FileUpload
control in an MVC5
project and I want to post multiple files from View
to Controller
using ViewModel
. Normally I have used some approach as AJAX
and Request.Files[n]
but I want to use ViewModel
as I already pass it to the Controller. I followed a good example File Uploads in ASP.NET MVC with View Models by @ChrisPratt
, but he does not talk about multiple uploads and there are some problems related to file upload control in MVC5
. So, could you please inform me what changes should be made in order to pass multiple file upload from View
to Controller
and get these multiple files in a foreach
loop.
View:
@model ExperimentViewModel
<input type="file" name="FileUpload" id="filer_input" multiple="multiple" >
<!-- or -->
@Html.TextBoxFor(m => m.FileUpload, new { type = "file" , id="filer_input"})
<script>
$('#filer_input').filer({
limit: null,
maxSize: null,
extensions: null,
uploadFile: {
url: //URL to which the request is sent {String}
data: //Data to be sent to the server {Object}
type: 'POST', //The type of request {String}
enctype: 'multipart/form-data', //Request enctype {String}
}
)};
function create(event) {
event.preventDefault();
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '@Url.Action("Create", "Experiment")',
cache: false,
dataType: "json",
data: formdata,
processData: false,
contentType: false
});
};
<script>
ViewModel:
public class ExperimentViewModel
{
//code omitted for brevity
[DataType(DataType.Upload)]
public HttpPostedFileBase FileUpload { get; set; }
}
Controller:
public JsonResult Insert([Bind(Exclude = null)] ExperimentViewModel model)
{
if (ModelState.IsValid)
{
//I have no idea how to retrieve the files.Count(), files in an IEnumerable<HttpPostedFileBase>
var files = model.FileUpload;
if(files != null && files.Count() > 0)
{
//???
}
}
}
Any help would be appreciated.
=============================== S O L V E D ================================
Here is the solution by @StephenMuecke. Many thanks for his huge help...
View:
ViewModel:
Controller: