Skip to main content
 首页 » 编程设计

c#之MVC5之如何使用 jquery ajax 将文件上传与模型一起传递给 Controller

2024年08月06日47qlqwjy

我需要使用 jquery ajax 将我的上传文件传递到我的 Controller 。

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 

Controller :

[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 属性,以便它可以将值回传给您的 Controller

<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) { 
    .... 
  }         
}); 

另请注意,文件输入需要在表单标签内