输入类型文件未在jquery ajax中序列化

时间:2017-09-25 07:48:51

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

当我将表单返回到提交时的jquery函数时,下面是剃刀代码。

 @model Slider
    @{

         Layout = null;
     }

    @using (Html.BeginForm("AddOrEdit", "Slider", FormMethod.Post, new { enctype  = "multipart/form-data" , onsubmit = "return   SubmitForm(this)" }))
    {
      @Html.HiddenFor(m => m.Id)



     <div class="form-group" style="height:270px;">
      @Html.LabelFor(m => m.ImageFile, new { @class = "blue-text", @style = 
      "font-size:16px", @id = "" })

 <input name="ImageFile" type="file"  />

 </div>

<div class="form-group">
     <input type="submit" value="Submit" class="btn btn-primary" />
     <input type="reset" value="Reset" class="btn" />
 </div>
 }

Jquery函数无法序列化输入文件类型并将其发送到控制器,除非我将其更改为json。但如果我将其更改为json,我将无法获得验证

  function SubmitForm(form) {
        debugger;
        $.validator.unobtrusive.parse(form);
        debugger;
        if ($(form).valid()) {
            debugger;
            $.ajax({
                type: "POST",
                url: form.action,
                //"datatype": "json"
                data: $(form).serialize(),
                success: function (data) {
                    if (data.success) {
                        Popup.dialog('close');
                        dataTable.ajax.reload();

                        $.notify(data.message, {
                            globalPosition: "top center",
                            className: "success"
                        })

                    } else {
                        Popup.dialog('close');

                        $.notify(data.message, {
                            globalPosition: "top center",
                            className: "error"
                        })
                    }
                }
            });
        }
        return false;
    }

1 个答案:

答案 0 :(得分:8)

尝试下面的代码并在ajax代码中进行一些更改。在代码中添加以下参数。

processData: false,
contentType: false,

在ajax开始之前添加var formData = new FormData($("#formID")[0]);行。

您应该使用FormData来使用ajax上传文件。 $(form).serialize()会为您提供关键和价值。您可以使用以下代码使用AJAX上传文件。

var formData = new FormData($(form)[0]);
$.ajax({
    url: form.action,
    type: form.method,
    data: formData,
    processData: false,
    contentType: false,

    success: function (response) {

    }
});
相关问题