0

I am using ASP.NET MVC and i want to pass the form data to my action but i noticed that the value of the variable filein my action after passing is null

public void ImgUpload(HttpPostedFileBase file)
    {
        bool isSavedSuccessfully = true;
        String fName = "";
        try
        {
            foreach (String filename in Request.Files)
            {
                file = Request.Files[filename];
                fName = file.FileName;
                if (file != null && file.ContentLength > 0)
                {
                    var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));                 
                    bool isExists = Directory.Exists(originalDirectory.ToString());
                    if (!isExists)
                        Directory.CreateDirectory(originalDirectory.ToString());
                    var path = string.Format("{0}\\{1}", originalDirectory.ToString(), file.FileName);
                    file.SaveAs(path);

                }




            }


        }
        catch (Exception e)
        {

            isSavedSuccessfully = false;
        }

    }

the Form has these two tags also :

        <div class="form-group">
        <label class="control-label" for="file">Filename:</label>
        <div class="col-md-10">
            <input type="file" name="file" id="file" />
        </div>

    </div>
    <div class="col-md-10 col-md-offset-2">
        <input id="submit" type="submit" value="Create" class="btn btn-default" />
    </div>

Here is the function :

        <script>
$('#submit').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;
    var formDataa = new FormData(this.form);
    $.ajax({
        url: "/ImageUploader/ImgUpload",
        type: "POST",
        data: JSON.stringify(formDataa),
        processData : false ,
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert("Done");
                $(element).closest("form").submit(); //<------------ submit form
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

</script>

Actually i am trying to upload file to the server and i think my problem is how or what is the proper type to handle posted data .

M Fuat
  • 1,330
  • 3
  • 12
  • 24
  • You have the wrong ajax options. Refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) for the correct options (`contentType: false,` and no `JSON.stringify()` or `traditional: true,`. And there is no point using `foreach (String filename in Request.Files)` since you already have a parameter `HttpPostedFileBase file` in the POST method –  Jul 17 '16 at 12:32
  • And what are you trying to do with `$(element).closest("form").submit();` in the success callback? What is the point of using ajax to submit once, and then do a normal submit again? –  Jul 17 '16 at 12:37
  • I have another form to be submitted after submitting the first one – M Fuat Jul 17 '16 at 12:54
  • But you code is submitting the same form a 2nd time. But why do you have 2 forms anyway –  Jul 17 '16 at 12:56
  • I am sorry i am little confusing i don't have two forms . Before everything i will call the action (ImgUpload) , after that i will submit the main form that has the two tags that i have mentioned . – M Fuat Jul 17 '16 at 13:04
  • Then read my 2nd comment - there is no point doing what you doing and you just degrading the performance of your app. You may as well make a normal submit. (and you previous comment says _I have **another form** to be submitted after submitting the first one_) And read the link in my first comment if you do want to post via ajax and stay on the same page (in which case remove the `$(element).closest("form").submit();`) –  Jul 17 '16 at 13:07
  • I think that i didn't explain very well First you will click on upload button and select the file that you want to upload when you click submit ajax code will just call the action that will upload the file to the server(ImgUpload) After that the original form will be submitted by this line ``$(element).closest("form").submit();`` original form has another controller and action So the major problem solved and now the file is uploaded successfully to the server but my new problem is that the original form hadn't submitted and i have this message `` "Error occurs on the Database level"`` – M Fuat Jul 17 '16 at 13:22
  • What your doing is pointless. Your uploading exactly the same data twice (but to 2 different controller methods). –  Jul 17 '16 at 13:24
  • I am little new but finally i understand you . I edited my code to use just one controller , one action with one form submitting . I was do ajax calling because i thought that if you make another controller to do special thing (image upload) and then back to the original one may be good . Anyway thank you :) – M Fuat Jul 17 '16 at 13:52

0 Answers0