I use a code like this to receive customer information. Along with my customer information, I must upload a file as well.
CSHTML File
@using (Html.BeginForm("AddPersonInfo", "Management", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmAddPerson" })) { @Html.AntiForgeryToken()
<div id="divControls" class="form inline">
<div class="form-group">
@Html.LabelFor(model => model.FName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-12">
@Html.EditorFor(model => model.FName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LName, htmlAttributes: new { @class = "control-label col-md-2"})
<div class="col-md-12">
@Html.EditorFor(model => model.LName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "control-label col-md-2", style = "float: right" })
<div class="col-md-12">
<input id="postedFile" type="file" data-buttonText="Select File">
@Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input style="float: right" id="btnSave" type="button" value="Save" class="btn btn-info" />
</div>
</div>
</div>
}
Java Script File
<script>
$(document).ready(function () {
$("#btnSave").click(function (e) {
e.preventDefault();
if ($("#frmAddPerson").valid()) {
var formData = new FormData();
var file = document.getElementById("postedFile").files[0];
formData.append("postedFile", file);
$.ajax({
url: "/Management/AddPersonInfo",
data: formData,
type: "Post",
dataType: "Json",
contentType: false,
processData: false,
success: function (result) {
alert("success")
},
error: function (result) {
alert("error");
}
});
}
});
});
</script>
Controller File
public ActionResult AddPersonInfo(PersonViewModel model, HttpPostedFileBase postedFile)
{
try
{
//
}
catch
{
//
}
}
In the AddPersonInfo in Controller, the file information (postedFile) will be received correctly But the form information (model) will be received null