如何使用View Models在ASP.NET MVC 5中使用jQuery.filer插件上传多个文件
我在MVC5
项目的FileUpload
控件上使用jQuery.filer ,我想使用ViewModel
将多个文件从View
到Controller
。 通常我使用了一些方法作为AJAX
和Request.Files[n]
但我想使用ViewModel
因为我已经将它传递给Controller。 我在 @ChrisPratt
ASP.NET MVC中使用View Models跟踪了一个很好的示例文件上传 ,但他没有谈到多个上传,并且在MVC5
存在与文件上传控制相关的一些问题。 那么,您能告诉我应该做些什么更改才能将多个文件从View
上传到Controller
并在foreach
循环中获取这些多个文件。
视图:
@model ExperimentViewModel @Html.TextBoxFor(m => m.FileUpload, new { type = "file" , id="filer_input"}) $('#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 }); };
视图模型:
public class ExperimentViewModel { //code omitted for brevity [DataType(DataType.Upload)] public HttpPostedFileBase FileUpload { get; set; } }
控制器:
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 var files = model.FileUpload; if(files != null && files.Count() > 0) { //??? } } }
任何帮助,将不胜感激。
===============================已解决 ================== ==============
这是@StephenMuecke的解决方案。 非常感谢他的巨大帮助……
视图:
@model ExperimentViewModel //Change 1 @Html.TextBoxFor(m => m.FileUpload, new { type = "file", multiple = "multiple" })
视图模型:
public class ExperimentViewModel { //code omitted for brevity //Change 4 [DataType(DataType.Upload)] public IEnumerable FileUpload { get; set; } }
控制器:
public JsonResult Insert(ExperimentViewModel model) //Change 5 { if (ModelState.IsValid) { //... } }