public async Task <IActionResult> Create(CreateOrUpdateBookViewModel book, IFormFile fImage) { if (ModelState.IsValid) { if (fImage == null || fImage.Length == 0) { ModelState.AddModelError("", "Uploaded file is empty or null."); DropdownForm(null); return(View(nameof(CreateOrUpdate), book)); } string image = UploadFileExtensions.UploadFile(fImage, "books"); if (!string.IsNullOrEmpty(image)) { book.Image = image; } book.Alias = book.Title.ToFriendlyUrl(); var viewModel = _mapper.Map <Book>(book); _context.Add(viewModel); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } DropdownForm(book); return(View(nameof(CreateOrUpdate), book)); }
private void DropdownForm(CreateOrUpdateBookViewModel book) { var authors = _context.Authors.Select(n => new { n.Id, n.Name }).ToList(); var categories = _context.Categories.Select(n => new { n.Id, n.Name }).ToList(); ViewData["AuthorId"] = new SelectList(authors, "Id", "Name", book != null ? book.AuthorId : 0); ViewData["CategoryId"] = new SelectList(categories, "Id", "Name", book != null ? book.AuthorId : 0); }
// GET: Admin/Books/Create public async Task <IActionResult> CreateOrUpdate(int?id) { var model = new CreateOrUpdateBookViewModel(); if (id != null) { var book = await _context.Books.FindAsync(id); model = _mapper.Map <CreateOrUpdateBookViewModel>(book); DropdownForm(model); } else { DropdownForm(null); } return(View(model)); }