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

我需要使用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"}) }  //rest of my strongly typed model here  //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 } } 

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

  // 

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

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

然后回复

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

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

您需要将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) { } })