简体   繁体   中英

How to Post file along with form data to MVC controller using Ajax?

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

jQuery Ajax call

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

Student Model

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

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

try this

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

Working Code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM