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

12,772

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;
}
Share:
12,772
Gopi
Author by

Gopi

!?!?!?!?

Updated on June 14, 2022

Comments

  • Gopi
    Gopi almost 2 years

    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.

  • Gopi
    Gopi about 5 years
    It did work for the form data but did not receive any file in studImg but Request.Files.Count was 1
  • Hamzeh.Ebrahimi
    Hamzeh.Ebrahimi about 5 years
    insert cache: false to ajax parameters
  • Gopi
    Gopi about 5 years
    It did not help
  • Ted Nyberg
    Ted Nyberg over 4 years
    The answer does not have a Student parameter in the CreateStudent action method, which I think is important in the OP.
  • Newclique
    Newclique almost 4 years
    You don't need a separate parameter for the upload. Changes: 1. Student class - public HttpPostedFileBase studImg {get; set;} ... 2. CreateStudent method: public ActionResult CreateStudent(Student student) {...} 3. $.ajax({ url: '/home/CreateStudent', ...} Everything else in the answer is correct. I tested this with MVC 5
  • Balasubramanian Ramamoorthi
    Balasubramanian Ramamoorthi almost 2 years
    will it work with mvc4.0 (visual studio 2012)?