Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 676
Gopi Avatar asked Jan 28 '19 05:01

Gopi


1 Answers

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;
}
like image 156
Hamzeh.Ebrahimi Avatar answered Nov 09 '22 08:11

Hamzeh.Ebrahimi