public async Task<ActionResult> Create(ContactAddEditViewModel contactAddEditViewModel) { var validImageTypes = new string[] { "image/gif", "image/jpeg", "image/pjpeg", "image/png" }; if (contactAddEditViewModel.PhotoUpload!=null &&!validImageTypes.Contains(contactAddEditViewModel.PhotoUpload.ContentType)) { ModelState.AddModelError("PhotoUpload", "Please choose either a GIF, JPG or PNG image."); } if (ModelState.IsValid) { if (contactAddEditViewModel.PhotoUpload != null) { var uploadDir = "~/photos"; var imagePath = Path.Combine(Server.MapPath(uploadDir), contactAddEditViewModel.PhotoUpload.FileName); var imageUrl = Path.Combine(uploadDir, contactAddEditViewModel.PhotoUpload.FileName); contactAddEditViewModel.PhotoUpload.SaveAs(imagePath); contactAddEditViewModel.PhotoPath = imageUrl; } var contact = AutoMapper.Mapper.Map<Contact>(contactAddEditViewModel); await _contactService.AddContactAsyn(contact); return RedirectToAction("Index"); } return View(contactAddEditViewModel); }
public async Task ContactAddShouldCreateWithRequiredFields() { var mock = new Mock<IContactService>(); var contactController = new ContactController(mock.Object); AutoMapper.Mapper.AddProfile(new ContactViewModelToContact()); var contactViewModel = new ContactAddEditViewModel{FirstName = "Test",Mobile = "012233555"}; var validationContext = new ValidationContext(contactViewModel, null, null); var validationResults = new List<ValidationResult>(); Validator.TryValidateObject(contactViewModel, validationContext, validationResults); foreach (var validationResult in validationResults) { contactController.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage); } var result = await contactController.Create(contactViewModel) as RedirectToRouteResult; Assert.NotNull(result); Assert.Equal("Index", result.RouteValues["action"]); }