Ajax.BeginForm is not working as expected
Asked Answered
H

2

0

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 ?

Hippogriff answered 18/8, 2015 at 21:17 Comment(11)
You cannot submit a file with Ajax.BeginForm. You can use FormData as shown in this answerLowborn
I use FormData, but still not work. It is return null. @StephenMueckeHippogriff
Then show the code you tried - I can't guess what mistakes you have made :). But in any case you only have a single file input but specify the parameter as IEnumerable<HttpPostedFileBase>. Use either multiple in the file input or change the parameter to just HttpPostedFileBaseLowborn
I change the parameter to HttpPostedFileBase, but still not work. What code you need ? This is all the code.Hippogriff
You said your tried the code in the link I gave you in my first comment (which does work - assuming your using a modern browser). If its not working for you, post the code you triedLowborn
I update the question when the first answer say that I should use FormData. I add new { enctype = "multipart/form-data" }to Ajax.BeginFrom and still not work. Please review the question again.Hippogriff
No, you need to read the answer in the ink I gave you - you need to use FormData which is NOT the same thing as enctype = "multipart/form-data"!Lowborn
Sorry for that, but you say I can't submit a file with ajax.beginform. There are many tutorials on youtube and on stackoverflow that show how to do that. Why your saying that ?Hippogriff
Because its a fact! (ajax does not allow multipart/form-data enctype)Lowborn
I will agree with you because I can't find any way to make ajax.BeginForm work. I suggest that you post an answer that show why ajax.BeginForm can't work and explain an alternative method to do ajax file upload. This will help other people who will see this question.Hippogriff
The link I gave you showed how to do this :) But I will add an answer later explaining why Ajax.BeginForm() cannot be used for submitting filesLowborn
L
2

You cannot submit files with Ajax.BeginForm(). The helper uses the jquery.unobtrusive-ajax.js file to submit the data using ajax functions which do not allow multipart/form-data enctype.

One option is to use FormData (but not supported in older browsers). Change the Ajax.BeginForm() to Html.BeginForm() and then handle the forms submit event

$('form').submit(function() {
  var formdata = new FormData($('form').get(0));
  $.ajax({
    url: '@Url.Action("YourActionName", "YourControllerName")',
    type: 'POST',
    data: formdata,
    processData: false,
    contentType: false,
    success: function() {
      .... // do something?
    }       
  });
});

In addition there are numerous jquery plugins that you can use for uploading files (14 of them are listed here)

Side note: Your file input allows selection of only one file, so your method parameter should be HttpPostedFileBase files (not IEnumerable<HttpPostedFileBase> files) or alternatively, include the multiple attribute in the file input.

Lowborn answered 19/8, 2015 at 2:20 Comment(0)
A
0

You need to specify the encoding type in your form.

   @using (Ajax.BeginForm("Upload", "ControllerName", 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">
    }
Avaavadavat answered 18/8, 2015 at 21:46 Comment(1)
Thanks for your answer, but the same problem. The form return null file.Hippogriff

© 2022 - 2024 — McMap. All rights reserved.