I am returning request failed but the save is working. What is wrong with this?

I am trying to upload multiple files. Everything seems to be working just fine but my controller is saying that the request failed. What am I doing wrong?

$(document).ready(function () {
    $('#RequestDetailFiles').on('click', function () {
        var data = new FormData();

        var files = $("#DetailFileUpload").get(0).files;

        // Add the uploaded image content to the form data collection
        if (files.length > 0) {
            for (i = 0; i < files.length; i++) {
                data.append("UploadedImage_" + i, files[i]);
            }
        }

        $('#DetailAppended').empty();
        $('#RequestDetailUploaded').empty();
        $("#RequestDetailUploaded").append('<p>Uploaded Files</p>');
        $("#RequestDetailUploaded").append('<ul id="DetailAppended">');
        for (var i = 0; i < files.length; i++)
            $("#DetailAppended").append('<li>' + files[i].name + '</li>');

        //append other form data.
        var requestId = $("#RequestId").val();
        data.append("Type", "Request Details");
        data.append("TypeId", "1");
        data.append("RequestId", requestId);

        // Make Ajax request with the contentType = false, and procesDate = false
        var ajaxRequest = $.ajax({
            type: "POST",
            url: "/uploadfile/uploadfile",
            contentType: false,
            processData: false,
            data: data,
            success: function (data) {
                //data is your result from controller
                if (files.success) {
                }
            },
            error: function (xhr) {
                //alert('error');
            }
        });

        ajaxRequest.done(function (xhr, textStatus) {
            alert("success");
            // Do other operation
        });
    });
});

Open in new window


  [HttpPost]
        public ActionResult UploadFile()
        {
            RequestContext dbContext = new RequestContext();
            Attachment thisAttachment = new Attachment();

            var attachments = new List<Attachment>();

            if (HttpContext.Request.Files.AllKeys.Any())
            {
                for (var i = 0; i < HttpContext.Request.Files.Count; i++)
                {
                    var httpPostedFile = HttpContext.Request.Files["UploadedImage_" + i];

                    var typeId = HttpContext.Request.Form["TypeId"];
                    var type = HttpContext.Request.Form["Type"];
                    var requestId = HttpContext.Request.Form["RequestId"];

                    if (httpPostedFile != null)
                    {
                        //Get the complete file path
                        var fileSavePath = Path.Combine(HttpContext.Server.MapPath("~/Attachments"), httpPostedFile.FileName);

                        thisAttachment = new Attachment()
                        {
                            Filename = httpPostedFile.FileName,
                            Path = fileSavePath,
                            TypeId = Convert.ToInt32(typeId),
                            CreatedOn = DateTime.Today,
                            RequestId = int.Parse(requestId)
                        };

                        dbContext.Attachments.Add(thisAttachment);
                        dbContext.SaveChanges(); 

                        // Save the uploaded file to "UploadedFiles" folder
                        httpPostedFile.SaveAs(fileSavePath);
                    }
                }
            }            
           return View();
        }

Open in new window

Natavia FinnieSenior Analyst Technical Focus ApplicationsAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chinmay PatelChief Technical NinjaCommented:
Hi Natavia,

Could you please tell me from which line it returns the error? Also have you tried putting debug point and see if it is coming from your controller? And what error code you are getting?

From the code snipped you have posted, both success and failure won't give any information to you. Error is commented out and success has no code in it.
if (files.success) {
                }
            },
            error: function (xhr) {
                //alert('error');
            }

Open in new window


And this additional code
        ajaxRequest.done(function (xhr, textStatus) {
            alert("success");
            // Do other operation
        });

Open in new window


I would check the value of textStatus before I provide the alert stating the operation was successful.

Regards,
Chinmay.
0
Miguel OzSoftware EngineerCommented:
For AJAX calls, your controller method shall return JsonResult as follows:
return Json("Your OK message goes here", JsonRequestBehavior.AllowGet);

Open in new window

that replaces:
return View();

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Kelvin McDanielSr. DeveloperCommented:
I saw this earlier but left it alone because @Chinmay and @Miguel are providing excellent assistance. Just saw it again as I was going through my first email purge of the morning and I realized that you're probably getting back a timeout error. As your code is currently written, this is going to happen when you start dealing with larger files and/or sets of smaller files that end up taking longer than your application's timeout threshold (whatever that may be). To get around this...

1. Change your controller method return type to System.Threading.Task<ActionResult> and use the async modifier.
2. Use the await modifier on anything in your method that is awaitable.
3. Unless you have a good reason not to, you should Dispose of anything that implements IDisposable, such as your DbContext (unless that ends up breaking things).

Those are a start for optimization. Also, you should consider abstracting all this away to a separate process. Why? Because all your users care about is that their files were successfully uploaded to the server. Everything else after that doesn't matter to them... and would ideally be handled by a custom Windows Service. That implementation is non-trivial and WAY outside the scope of your question, however.

Good Luck!
0
Omer RasheedCommented:
You need to see the response received from server. If it's an error then go throw the error message which will provide the inside detail of the cause.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.