如何使用Ajax将文件和表单数据一起发布到MVC控制器?

时间:2019-01-28 05:39:37

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

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

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控制器

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

学生模型

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

尽管我能够在Request中获取文件,但是studentDetails参数在MVC控制器中始终为null。

1 个答案:

答案 0 :(得分:2)

尝试

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

然后更改操作以获取如下图像

[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;
}