如何使用Ajax将文件和表单数据一起发布到MVC控制器? [英] How to Post file along with form data to MVC controller using Ajax?

查看:181
本文介绍了如何使用Ajax将文件和表单数据一起发布到MVC控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to post file along with other form data to MVC controller using jquery Ajax.

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.

Though I was able to get the file in the Request, the studentDetails parameter is always null in MVC controller.

推荐答案

尝试一下

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

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

then change your action to get image as follow

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

这篇关于如何使用Ajax将文件和表单数据一起发布到MVC控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆