将FormData传递给AJAX调用时如何修复HttpPostedFileBase null

时间:2019-06-18 21:04:38

标签: javascript jquery ajax asp.net-mvc asp.net-ajax

我有一个AJAX调用,它将数据和文件一起传递到ViewModel并调用控制器:

function fncInsTrainingLog()
{
    var trainingtitle = getValOf("trainingTitle");
    var ImageFile = $('#imageUploadForm')[0].files[0];

    var sdata = {
        TrainingTitle :trainingtitle,
        ImageFile : ImageFile
    }

    $.ajax({
        url: "/Capability/InsTrainingLog",
        type: "POST",
        data: JSON.stringify(sdata),
        contentType: "application/json",
        dataType: "json",
        success: function () {
            location.reload();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("A problem has been encountered. Please contact the web administrator.");
        }
    });
} 

这是我的控制人:

[HttpPost]
public JsonResult InsTrainingLog(TrainingModel trainingModel)
{

    // Psuedo code to save file to drive
    // get file from TrainingModel 
    // save(file)

    string sp = "usp_InsTrainingLog";

    object[] param =
    {
        "@TrainingTitle", trainingModel.TrainingTitle
    };

    dbHelper.ExecuteProcedureNonQuery(sp, param);
    var result = param;

    return Json(result, JsonRequestBehavior.AllowGet);
}

ViewModel:

   public sealed class TrainingModel
    {
        public HttpPostedFileBase ImageFile { get; set; }
        public string TrainingTitle { get; set; }

    }

ImageFile中的TrainingModel返回null,但是TrainingTitle可以。为什么ViewModel无法从AJAX调用中读取文件?

如何将文件传递到ViewModel并将图像保存到PC?

2 个答案:

答案 0 :(得分:1)

您需要将AJAX调用与FormData()一起使用,将contentType更改为contentType: false,然后添加processData: false

我转载了并且有效

var trainingtitle = $("#trainingTitle").val();
                var ImageFile = $('#imageUploadForm')[0].files[0];

                var formData = new FormData();
                formData.append('TrainingTitle', trainingtitle);
                formData.append('ImageFile', ImageFile);


                $.ajax({
                    url: "/Product/InsTrainingLog",
                    type: "POST",
                    data: formData,
                    contentType: false,
                    processData: false,
                    dataType: "json",
                    success: function () {
                        location.reload();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("A problem has been encountered. Please contact the web administrator.");
                    }
                });



Updated cshtml


    <div id="uploadForm">
                    <input type="text" name="TrainingTitle" id="trainingTitle" />
                    <input type="file" name="ImageFile" id="imageUploadForm" />
                    <button type="button" onclick="fncInsTrainingLog()">Submit</button>
                </div>

    function fncInsTrainingLog() {
                var trainingtitle = $("#trainingTitle").val();
                var ImageFile = $('#imageUploadForm')[0].files[0];

                var formData = new FormData();
                formData.append('TrainingTitle', trainingtitle);
                formData.append('ImageFile', ImageFile);
                //var sdata = {
                //    TrainingTitle: trainingtitle,
                //    ImageFile: ImageFile
                //}

                $.ajax({
                    url: "/Product/InsTrainingLog",
                    type: "POST",
                    data: formData,
                    contentType: false,
                    processData: false,
                    dataType: "json",
                    success: function () {
                        location.reload();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("A problem has been encountered. Please contact the web administrator.");
                    }
                });
            }

答案 1 :(得分:0)

我会使用$ .ajaxForm()...

@using (Html.BeginForm())
{
    <div id="status"></div>

    <input type="text" name="TrainingTitle" />
    <input type="file" name="ImageFile" accept="image/*" />
    <input type="submit" value="Upload File to Server" />
}


<script>
    (function () {
       var status = $('#status');
        $('form').ajaxForm({
            complete: function (xhr) {
                    status.html(xhr.responseText);
                }
            }
        });
    })();
</script>

代码未经测试!