Esempio n. 1
0
 public ArtistViewModel(Artist artistEntity)
 {
     ID = artistEntity.ID;
     Name = artistEntity.Name;
     Image = artistEntity.Image;
 }
        public ActionResult Edit([Bind(Include = "ID,Name,FileUpload")] ArtistViewModel artistVm)
        {
            if (ModelState.IsValid)
            {
                var artistEntity = new Artist
                {
                    ID = artistVm.ID,
                    Name = artistVm.Name
                };

                // Save the file
                if(artistVm.FileUpload != null)
                {
                    string fileName = string.Empty;
                    string filePath = string.Empty;

                    try
                    {
                        fileName = artistVm.FileUpload.FileName;
                        filePath = @"C:\GitHub\MusicBox\MusicBox\MusicBox.Web\Content\Images\" + artistVm.FileUpload.FileName;
                        artistVm.FileUpload.SaveAs(filePath);

                        artistEntity.Image = fileName;
                    }
                    catch (Exception e)
                    {
                        if (!string.IsNullOrEmpty(filePath))
                        {
                            if (System.IO.File.Exists(filePath))
                                System.IO.File.Delete(filePath); //here is the error
                        }
                    }
                    finally
                    {
                        artistVm.FileUpload.InputStream.Close();
                        artistVm.FileUpload.InputStream.Dispose();
                        GC.Collect();
                    }

                }

                db.Entry(artistEntity).State = EntityState.Modified;
                db.SaveChanges();

                var artistEntities = db.Artists.ToList();
                var artistsVm = from artist in
                                artistEntities
                                select new ArtistViewModel(artist);

                return PartialView("_ArtistList", artistsVm);
            }
            return View(artistVm);
        }