【发布时间】:2016-10-08 07:59:42
【问题描述】:
我在MVC5 项目中的FileUpload 控件上使用jQuery.filer,我想使用ViewModel 将多个文件从View 发布到Controller。通常我使用AJAX和Request.Files[n]这样的方法,但我想使用ViewModel,因为我已经将它传递给了控制器。我跟着@ChrisPratt的一个很好的例子File Uploads in ASP.NET MVC with View Models,但他并没有谈到多次上传,在MVC5中存在一些与文件上传控制相关的问题。那么,您能否告诉我应该进行哪些更改才能将多个文件上传从View 传递到Controller 并在foreach 循环中获取这些多个文件。
查看:
@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; }
}
控制器:
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)
{
//???
}
}
}
任何帮助将不胜感激。
【问题讨论】:
-
属性必须是
IEnumerable<HttpPostedFileBase> FileUpload才能接受多个文件(注意它需要是@Html.TextBoxFor(m => m.FileUpload, new { type = "file", multiple = "multiple" })才能添加multiple属性) -
可以传给Controller。另一方面,我使用jQuery.filer,并且必须为FileUploader 提供一个ID 作为filer_input 才能使用jQuery.filer。但是,当使用 id 作为“filer_input”或将“FileUpload”属性名称更改为“filer_input”时,模型数据将作为 null 传递给控制器(model.FileUpload 或 model.filer_input)。查看 Firebug 的 Network 面板时,我看到模型数据以 Content-Disposition: form-data; 的形式传递。名称="文件上传[]";文件名=“test.xlsx”(添加“[]”)>>>
-
>>> 你知道为什么我用jQuery.filer时数据不能传给Controller吗?我必须将数据添加到 AJAX 帖子吗?
-
以前从未见过那个插件。稍后再看看。
-
谢谢,你可以看看github.com/avral/jquery.filer上的参数说明
标签: jquery ajax asp.net-mvc file-upload