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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With