如何使用View Models在ASP.NET MVC 5中使用jQuery.filer插件上传多个文件

时间:2016-10-08 07:59:42

标签: jquery ajax asp.net-mvc file-upload

我在FileUpload项目的MVC5控件上使用jQuery.filer,我希望使用{{1}将多个文件从View发布到Controller }}。通常我使用了一些方法ViewModelAJAX但我想使用Request.Files[n],因为我已经将它传递给Controller。我按照ViewModel跟踪了一个很好的示例File Uploads in ASP.NET MVC with View Models,但他没有谈到多次上传,并且在@ChrisPratt中存在与文件上传控制相关的一些问题。那么,您能否告诉我,为了将多个文件从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>


控制器:

public class ExperimentViewModel
{
    //code omitted for brevity

    [DataType(DataType.Upload)]
    public HttpPostedFileBase FileUpload { get; set; }
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

=============================== 已解决 ======== ========================

以下是 @StephenMuecke 的解决方案。非常感谢他的巨大帮助...

<强> 查看:

@model ExperimentViewModel

//Change 1
@Html.TextBoxFor(m => m.FileUpload, new { type = "file", multiple = "multiple" })

<script>        
    function create(event) {
        event.preventDefault();

        //Change 2 : Because jquery.filer adds "[]" to the Name parameter!!!
        $('#FileUpload').attr('name', 'FileUpload');

        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
        });
    };

    $('#FileUpload').filer({

    //code omitted for brevity

    //Change 3: Comment out uploadFile section
    //uploadFile: { ... }

    });
<script>


视图模型:

public class ExperimentViewModel
{
    //code omitted for brevity

    //Change 4
    [DataType(DataType.Upload)]
    public IEnumerable<HttpPostedFileBase> FileUpload { get; set; }
}


控制器:

public JsonResult Insert(ExperimentViewModel model) //Change 5
{
    if (ModelState.IsValid)
    {
        //...   
    }
}