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;
}
Comments
-
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 about 5 yearsIt did work for the form data but did not receive any file in studImg but Request.Files.Count was 1
-
Hamzeh.Ebrahimi about 5 yearsinsert cache: false to ajax parameters
-
Gopi about 5 yearsIt did not help
-
Ted Nyberg over 4 yearsThe answer does not have a
Student
parameter in theCreateStudent
action method, which I think is important in the OP. -
Newclique almost 4 yearsYou 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 almost 2 yearswill it work with mvc4.0 (visual studio 2012)?