MVC5 - 如何使用jquery ajax将fileupload与模型一起传递给控制器

时间:2015-03-31 10:50:44

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

我需要使用jquery ajax将我的上传文件传递给我的控制器。

JS:

$('#btnpopupreg').click(function () {
        $.ajax({
            type: 'POST',
            url: '/Membership/Register',
            data: $('#frmRegister').serializeArray(),
            dataType: 'json',
            headers: fnGetToken(),
            beforeSend: function (xhr) {

            },
            success: function (data) {
                //do something
            },
            error: function (xhr) {

            }
        })
})

查看:

@model Test.RegisterViewModel

@{
       using Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With {.id = "frmPopUpRegister", .enctype = "multipart/form-data"})
}

<input type="file" />
//rest of my strongly typed model here
<input type="button" value="BUTTON" />
//rest of the code here

控制器:

[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]

public void Register(RegisterViewModel model)
{

    if (Request.Files.Count > 0) { //always 0

    }

    if (ModelState.IsValid) {
          //do something with model
    }
}

我可以很好地获取模型值,但Request.Files总是返回null。我也尝试过使用HttpPostedFileBase但它总是返回null

[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]

public void Register(RegisterViewModel model, HttpPostedFileBase files)
{
    //files always null

    if (ModelState.IsValid) {
          //do something with model
    }
}

3 个答案:

答案 0 :(得分:3)

首先,您需要为文件控件提供name属性,以便它可以将值回发给您的控制器

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

然后序列化您的表单和相关文件

var formdata = new FormData($('form').get(0));

并以

发回
$.ajax({
  url: '@Url.Action("Register", "Membership")',
  type: 'POST',
  data: formdata,
  processData: false,
  contentType: false, 
  success: function (data) {
    ....
  }        
});

另请注意,文件输入必须位于表单标记内

答案 1 :(得分:0)

您需要将FormData与contentType,processData设置组合使用为false:

    var formData = new FormData();
        formData.append("userfile", $('#frmRegister input[type="file"]')[0].files[0]);
        // append the file in the form data
    $.ajax({
      type: 'POST',
      url: '/Membership/Register',
      data: formdata, // send it here
      dataType: 'json',
      contentType:false, // this
      processData:false, // and this should be false in case of uploading files
      headers: fnGetToken(),
      beforeSend: function(xhr) {

      },
      success: function(data) {
        //do something
      },
      error: function(xhr) {

      }
    })

答案 2 :(得分:0)

<input type="file" id="LogoImage" name="image" />
<script>

var formData = new FormData($('#frmAddHotelMaster').get(0));

var file = document.getElementById("LogoImage").files[0];

formData.append("file", file);


        $.ajax({
            type: "POST",
            url: '/HotelMaster/SaveHotel',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (response) {
                swal({
                        title: "Good job!",
                        text: "Data Save successfully!",
                        type: "success"
                    });
                    $('#wrapper').empty();
                    $('#wrapper').append(htmlData);
            },
            error: function (error) {
                alert("errror");
            }
        });
</script>

public ActionResult SaveHotel(HotelMasterModel viewModel, HttpPostedFileBase file)
{

            for (int i = 0; i < Request.Files.Count; i++)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
                file.SaveAs(path);
            }
return View();
}