Fixed a nasty bug in my MyFabricStash Web App!

I've been trying to fix this bug for quite a while now and I'm so proud of myself, I finally figured it out! It may not be the prettiest solution. I'm sure there is a hundred different ways you could have solved this but it works! 

Here's the bug

On the Edit page of my app, whenever I wanted to Add Quantity or other properties on an existing Fabric, I had to click on Choose File and re-select the existing image or it would save in the database as null.

How I fixed it

In the Edit action of the FabricController, in the HttpPost method, I added a check if the File textbox value submitted is null (which it would be if I did not select a new image), then get the existing image's ImagePath from the database and pass it to the model, fabric.ImagePath. If the File textbox value is not null, get the Filename and save it in the File to the server and the ImagePath (filename) in the database. See the code below

            if (ModelState.IsValid)
                var path = Server.MapPath("~/images/");

                if (fabric.File == null)
                    var imagepath = db.Fabrics.Where(x => x.FabricId == fabric.FabricId)
                        .Select(x => x.ImagePath).FirstOrDefault();
                    fabric.ImagePath = imagepath;

                } else
                    var filename = Path.GetFileName(fabric.File.FileName);
                    fabric.File.SaveAs(path + filename);
                    fabric.ImagePath = fabric.File.FileName;

Still needs to be tested on my dev site but, It totally works! I'm a genius! :)

Add comment