I have a very strange problem with Aajx.BeginForm. I have this code :
In view :
@using (Ajax.BeginForm("Upload", "Profile", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<input type="file" name="files"><br>
<input type="submit" value="Upload File to Server">
}
In controller :
[HttpPost]
[ValidateAntiForgeryToken]
public void Upload(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// TODO: need to define destination
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
file.SaveAs(path);
}
}
}
}
The problem is that I get null file when the form is submit. I read many question that is the same of my question, but most of the answers was that the name of input type="file" is not as the same name of the parameter name in the controller. I found some examples, I try this one which is almost the same of my code except for the jquery files, so I tried to replace the jquery files with these files :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
And here is the surprise !!. When the form is submit, I get the file but the form is post back. It is work as there is no ajax. I search in google for Ajax.BeginFrom that is post back and found many solutions in stackoverflow and most of of the answers was that jquery.unobtrusive-ajax file must be included in the page. It like a circle of problems, once you solve one you get another. Does I miss something ?
Ajax.BeginForm
. You can useFormData
as shown in this answer – LowbornIEnumerable<HttpPostedFileBase>
. Use eithermultiple
in the file input or change the parameter to justHttpPostedFileBase
– LowbornFormData
which is NOT the same thing asenctype = "multipart/form-data"
! – LowbornAjax.BeginForm()
cannot be used for submitting files – Lowborn