コード例 #1
0
        public async Task <IActionResult> Edit(int?id, byte[] rowVersion)
        {
            string[] fieldsToBind = new string[] { "Name", "RowVersion" };
            if (id == null)
            {
                return(NotFound());
            }
            var categoryToUpdate = await _context.Category.FindAsync(id);

            if (categoryToUpdate == null)
            {
                Category deletedCategory = new Category();
                await TryUpdateModelAsync(deletedCategory, "", s => s.ID, s => s.Name, s => s.RowVersion);

                ModelState.AddModelError(string.Empty, "Unable to save your changes because the " +
                                         "category has been deleted by another user.");
                return(View(deletedCategory));
            }
            if (await TryUpdateModelAsync(categoryToUpdate, "", s => s.ID, s => s.Name, s => s.RowVersion))
            {
                try
                {
                    _context.Entry(categoryToUpdate).OriginalValues["RowVersion"] = rowVersion;
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exEntry          = ex.Entries.Single();
                    var currentUIValues  = (Category)exEntry.Entity;
                    var databaseCategory = exEntry.GetDatabaseValues();
                    if (databaseCategory == null)
                    {
                        ModelState.AddModelError(string.Empty, "Unable to save your changes because " +
                                                 "the category has been deleted by another user.");
                    }
                    else
                    {
                        var databaseCategoryValues = (Category)databaseCategory.ToObject();
                        if (databaseCategoryValues.Name != currentUIValues.Name)
                        {
                            ModelState.AddModelError("Name", "Current value in database: " + databaseCategoryValues.Name);
                        }
                        ModelState.AddModelError(string.Empty, "The record has been modified by  " +
                                                 "another user after you loaded the screen. Your changes have not yet been saved. " +
                                                 "The new values in the database are shown below. If you want to overwrite these values" +
                                                 " with your changes then click save otherwise go back to the categories page.");
                        categoryToUpdate.RowVersion = (byte[])databaseCategoryValues.RowVersion;
                        ModelState.Remove("RowVersion");   //This is must because ModelState has the old RowVersion value. In the Razor Page the ModelState value for a field takes precedence over the model property values when bot are present
                    }
                }
            }
            return(View(categoryToUpdate));
        }
コード例 #2
0
        public async Task <IActionResult> Upload(IFormFile[] files)
        {
            bool   allValid     = true;
            string inValidFiles = "";

            //check the user has entered a file
            if (files.Length != 0)
            {
                //if the user has entered less than 10 files
                if (files.Length <= 10)
                {
                    foreach (var file in files)
                    {
                        if (!ValidateFile(file))
                        {
                            allValid      = false;
                            inValidFiles += ", " + Path.GetFileName(file.FileName);
                        }
                    }
                    //if they are valid then try to save them to disk
                    if (allValid)
                    {
                        foreach (var file in files)
                        {
                            try
                            {
                                SaveFileToDiskAsync(file);
                            }
                            catch (Exception)
                            {
                                ModelState.AddModelError("FileName", "Sorry an error occurred saving the file to disk, please try again");
                            }
                        }
                    }
                    //else add an error listing out the invalid files
                    else
                    {
                        ModelState.AddModelError("FileName", "All files must be gif, png, jpeg or jpg and less than 2MB in size.The following files" + inValidFiles + " are not valid");
                    }
                }
                //the user has entered more than 10 files
                else
                {
                    ModelState.AddModelError("FileName", "Please only upload up to ten files at a time");
                }
            }
            else
            {
                //if the user has not entered a file return an error message
                ModelState.AddModelError("FileName", "Please choose a file");
            }

            if (ModelState.IsValid)
            {
                bool   duplicates     = false;
                bool   otherDbError   = false;
                string duplicateFiles = "";

                foreach (var file in files)
                {
                    //try and save each file
                    var productToAdd = new ProductImage {
                        FileName = Path.GetFileName(file.FileName)
                    };
                    try
                    {
                        _context.Add(productToAdd);
                        await _context.SaveChangesAsync();
                    }
                    //if there is an exception check if it is caused by duplicate file
                    catch (DbUpdateException ex)
                    {
                        SqlException innerException = ex.InnerException as SqlException;
                        if (innerException != null && innerException.Number == 2601)
                        {
                            duplicateFiles += "," + Path.GetFileName(file.FileName);
                            duplicates      = true;
                            _context.Entry(productToAdd).State = EntityState.Detached;
                        }
                        else
                        {
                            otherDbError = true;
                        }
                    }
                }

                //add a list of duplicate files to the error message
                if (duplicates)
                {
                    ModelState.AddModelError("FileName", "All files uploaded except the files" + duplicateFiles
                                             + ", which already exist in the system ." + " Please delete them and try again if you wish to re-add them");
                    return(View());
                }
                else if (otherDbError)
                {
                    ModelState.AddModelError("FileName", "Sorry an error has occurred saving to the database, please try again");
                    return(View());
                }

                return(RedirectToAction(nameof(Index)));
            }
            return(View());
        }