gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:02 25 4
gpt4 key购买 nike

我需要使用 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) {
....
}
});

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

关于c# - MVC5 - 如何使用 jquery ajax 将文件上传与模型一起传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29366904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com