gpt4 book ai didi

c# - 如何使用 Ajax 将文件和表单数据一起发布到 MVC Controller ?

转载 作者:行者123 更新时间:2023-11-30 22:56:32 25 4
gpt4 key购买 nike

我正在尝试使用 jquery Ajax 将文件和其他表单数据一起发布到 MVC Controller 。

jQuery Ajax 调用

function SaveStundent () {
var formData = new FormData();

var file = document.getElementById("studImg").files[0];
formData.append("studImg", file);

var studentDetails = {
Name: $('#txtName').val().trim()
};

formData.append("studentDetails", studentDetails);

$.ajax({
type: "POST",
url: "@(Url.Action("CreateStudent", "Student"))",
data: formData,
processData: false,
contentType: false,
success: function (response) {
}
});
}

MVC Controller

[HttpPost]
public ActionResult CreateStudent(Student studentDetails)
{
// ...
}

学生模型

public class Student
{
public string Name { get; set; }
}

虽然我能够在请求中获取文件,但是 MVC Controller 中的 studentDetails 参数始终为 null。

最佳答案

试试这个

function SaveStundent () {
var formData = new FormData();

var file = document.getElementById("studImg").files[0];
formData.append("studImg", file);

var Name= $('#txtName').val().trim()

formData.append("Name", Name);

$.ajax({
type: "POST",
url: "@(Url.Action("CreateStudent", "Student"))",
data: formData,
processData: false,
contentType: false,
success: function (response) {
}
});
}

然后改变你的 Action 来获取图像如下

[HttpPost]
public ActionResult CreateStudent(Student studentDetails,HttpPostedFileBase studImg)
{
// ...
}

工作代码

<form id="frm" enctype="multipart/form-data">
<input type="file" name="studImg" id="studImg" />
<input type="text" name="txtName" id="txtName" />
<input type="button" value="Save" onclick="SaveStundent()" />
</form>

<script>
function SaveStundent () {
var formData = new FormData();
var file = document.getElementById("studImg").files[0];
formData.append("studImg", file);

var Name = $('#txtName').val().trim()
formData.append("Name", Name);

$.ajax({
type: "POST",
url: "@(Url.Action("CreateStudent", "Student"))",
data: formData,
processData: false,
contentType: false,
success: function (response) {
}
});
}
</script>

public ActionResult CreateStudent(string Name, HttpPostedFileBase studImg)
{
return null;
}

关于c# - 如何使用 Ajax 将文件和表单数据一起发布到 MVC Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54396101/

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