在MVC

时间:2018-09-20 02:14:18

标签: c# jquery asp.net-core-mvc

检查下面的jquery代码。在这里,我从html抓取文件,然后通过ajax调用将其发布到我的Controller Post方法。正如您所见,从Controller post方法中,我成功地收到了名为files的变量中的文件。但是我的问题是如何从此ajax调用中发送另外两个文本参数-typeid,然后又如何从带有该文件的控制器中获取该值?基本上我也必须使用这些文本值来获取该文件。那怎么可能? Ajax和控制器需要哪些更改?

HTML:

<div class="col-sm-3" style="float:left;">
                        <label class="btn btn-outline-dark btn-block">
                            Browse...
                            <span id="uploaded-file-name" style="font-style: italic"></span>
                            <input id="file-upload" type="file" name="file"
                                   onchange="$('#uploaded-file-name').text($('#file-upload')[0].value);" hidden>
                        </label>
                    </div>
                    <div class="col-sm-2" style="float:left;">
                        <button class="btn btn-dark" id="start_upload">Start Upload</button>
                    </div>

jQuery ajax:

//file upload
        $("#start_upload").click(function (evt) {
            var fileUpload = $("#file-upload").get(0);
            var files = fileUpload.files;
            var data = new FormData();
            for (var i = 0; i < files.length; i++) {
                data.append(files[i].name, files[i]);
            }
            $.ajax({
                type: "POST",
                url: "/Products/UploadFiles",
                contentType: false,
                processData: false,
                data: data,
                success: function (message) {
                    alert(message);
                },
                error: function () {
                    alert("There was error uploading files!");
                }
            });
        });

MVC .net核心控制器:

[HttpPost]
public IActionResult UploadFiles()
{
    //file upload process
    var files = Request.Form.Files;

    string type = "";
    int id = ;


}

2 个答案:

答案 0 :(得分:2)

您可以将其他输入字段值添加到FormData对象。

我将从创建一个用于接受ajax有效负载的视图模型开始

public class UploadVm
{
    public string Type { set; get; }
    public string Id { set; get; }
    public HttpPostedFileBase File { set; get; }
}

现在,在您的视图中,再添加2个输入元素以从用户读取此值

<input id="id"   type="text" />
<input id="type" type="text" />

现在,在您的Ajax调用代码中,再向FormData对象添加2个项目。

$("#start_upload").click(function (evt) {

    var fileUpload = $("#file-upload").get(0);
    var files = fileUpload.files;
    var data = new FormData();

    for (var i = 0; i < files.length; i++) {
        data.append("File", files[i]);
    }

    //Add the input element values
    data.append("Type", $("#type").val());
    data.append("Id", $("#id").val());

    $.ajax({
        type: "POST",
        url: "/Products/UploadFiles",
        contentType: false,
        processData: false,
        data: data,
        success: function (message) {
            console.log(message);
        },
        error: function () {
            alert("There was error uploading files!");
        }
    });

});

现在在服务器端,您可以使用我们的新视图模型作为action方法的参数。进行ajax调用后,模型绑定器将能够映射从请求接收的数据并将其映射到我们的UploadVm视图模型对象的属性。

[HttpPost]
public ActionResult UploadFiles(UploadVm model)
{
    // to do : read values of model and use it
    // to do : return something
}

答案 1 :(得分:2)

我在这里要做的是,只需将带有值的键插入jquery的FormData() obj中,然后就可以从控制器中获取它了。如果您想进一步了解FormData(),请read here

将您的jquery更改为此-

//file upload
        $("#start_upload").click(function (evt) {
            var fileUpload = $("#file-upload").get(0);
            var files = fileUpload.files;
            var data = new FormData();
            data.append('type', 'your_type');
            data.append('id', '1');

            for (var i = 0; i < files.length; i++) {
                data.append(files[i].name, files[i]);
            }
            $.ajax({
                type: "POST",
                url: "/Products/UploadFiles",
                contentType: false,
                processData: false,
                data: data,
                success: function (message) {
                    alert(message);
                },
                error: function () {
                    alert("There was error uploading files!");
                }
            });
        });

然后通过控制器的键获取这些值:

[HttpPost]
public IActionResult UploadFiles()
{
    //file upload process
    var files = Request.Form.Files;
    string type = Request.Form.Where(x => x.Key == "type").FirstOrDefault().Value;
    string id = Request.Form.Where(x => x.Key == "id").FirstOrDefault().Value;

}