// GET: Client/Edit/5 public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } Client client = await _context.Clients.FindAsync(id); if (client == null) { return(NotFound()); } ClientEditViewModel model = new ClientEditViewModel { Id = client.Id, Name = client.Name, Surname = client.Surname, Email = client.Email, PhoneNumber = client.PhoneNumber, IsAdult = client.IsAdult }; return(View(model)); }
public async Task <IActionResult> EditClient( Guid?siteId, string clientId = null) { var selectedSite = await siteManager.GetSiteForDataOperations(siteId); if (!string.IsNullOrEmpty(clientId)) { ViewData["Title"] = string.Format(CultureInfo.CurrentUICulture, sr["{0} - Edit Client"], selectedSite.SiteName); } var model = new ClientEditViewModel(); model.SiteId = selectedSite.Id.ToString(); model.NewClient.SiteId = model.SiteId; if (!string.IsNullOrEmpty(clientId)) { var client = await clientsManager.FetchClient(model.SiteId, clientId); model.CurrentClient = new ClientItemViewModel(model.SiteId, client); } if (model.CurrentClient == null) { ViewData["Title"] = string.Format(CultureInfo.CurrentUICulture, sr["{0} - New Client"], selectedSite.SiteName); var currentCrumbAdjuster = new NavigationNodeAdjuster(Request.HttpContext); currentCrumbAdjuster.KeyToAdjust = "EditClient"; currentCrumbAdjuster.AdjustedText = sr["New Client"]; currentCrumbAdjuster.AddToContext(); } return(View(model)); }
public ClientEditViewModel Update(ClientEditViewModel ClientEditViewModel) { Client Client = ClientRepo.Update(ClientEditViewModel.ToModel()); unitOfWork.commit(); return(Client.ToEditableViewModel()); }
public IActionResult Edit(string id) { //Client client = _context.Set<Client>().Find(new Guid(id)); Client client = _context.Set <Client>() .FindBy(c => c.ClientId == new Guid(id)) .Include(cl => cl.ClientImages) .FirstOrDefault(); if (client == null) { return(NotFound($"Клиент с id: {id} не найден")); } ClientEditViewModel clientEdited = new ClientEditViewModel(); clientEdited.ClientId = id; clientEdited.Name = client.Name; clientEdited.ShortDescription = client.ShortDescription; clientEdited.Description = client.Description; clientEdited.HttpUrl = client.HttpUrl; if (client.ClientImages.FirstOrDefault() != null) { clientEdited.ImagePath = client.ClientImages.FirstOrDefault().Path; clientEdited.ImageIsPoster = client.ClientImages.FirstOrDefault().IsPoster; } else { clientEdited.ImagePath = ""; clientEdited.ImageIsPoster = false; } return(View(clientEdited)); }
// GET: Clients/Edit/5 public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var client = await _context.Clients.FindAsync(id); if (client == null) { return(NotFound()); } ViewData["ZcountyId"] = new SelectList(_context.Zcounty.OrderBy(m => m.county), "ZcountyId", "county", client.ZcountyId); ViewData["ZraceId"] = new SelectList(_context.Zrace.OrderBy(m => m.race), "ZraceId", "race", client.ZraceId); ViewData["ZinsuranceId"] = new SelectList(_context.Zinsurance.Where(m => m.active).OrderBy(m => m.insurance), "ZinsuranceId", "insurance", client.ZinsuranceId); ClientEditViewModel clientEditViewModel = new ClientEditViewModel(); clientEditViewModel.Client = await _context.Clients.FirstOrDefaultAsync(m => m.ClientId == client.ClientId); clientEditViewModel.Inquiries = await _context.ClientServices .Where(cs => cs.ClientId == client.ClientId) .Include(cs => cs.Zstatus) .Include(cs => cs.Service) .Include(cs => cs.Zworker) .OrderByDescending(cs => cs.recdate) .ToListAsync(); return(View(clientEditViewModel)); }
public IActionResult Edit(ClientEditViewModel model) { if (ModelState.IsValid) { /// return(View(model)); } return(View(model)); }
public IActionResult Edit(int id, ClientEditViewModel client) { if (!ModelState.IsValid) { return(View(client)); } client.Persist(id, context); return(RedirectToAction(actionName: nameof(Index))); }
// Ação de Novo Cliente public ActionResult New() { //Cria nova instância vazia de ClientViewModel var editViewModel = new ClientEditViewModel { Client = new Client() }; //Retorna a ClientViewModel para a view ClienteForm(novo cliente ou edição de cliente) return(View("ClientForm", editViewModel)); }
public async Task <IActionResult> Edit(int id, ClientEditViewModel clientEditViewModel) { Client client = clientEditViewModel.Client; if (client.dob != null) { DateTime temp = client.dob ?? DateTime.Now; var tod = DateTime.Today; var age = tod.Year - temp.Year; if (temp.Date > tod.AddYears(-age)) { client.age = age--; } else { client.age = age; } } if (id != client.ClientId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(client); await _context.SaveChangesAsync(); TempData["Alert"] = String.Format("Saved Changes to Client: {0} {1}", client.cfirst, client.clast); } catch (DbUpdateConcurrencyException) { if (!ClientExists(client.ClientId)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Edit", "Clients", new { id = client.ClientId })); } ViewData["ZcountyId"] = new SelectList(_context.Zcounty.OrderBy(m => m.county), "ZcountyId", "county", client.ZcountyId); ViewData["ZraceId"] = new SelectList(_context.Zrace.OrderBy(m => m.race), "ZraceId", "race", client.ZraceId); ViewData["ZinsuranceId"] = new SelectList(_context.Zinsurance.Where(m => m.active).OrderBy(m => m.insurance), "ZinsuranceId", "insurance", client.ZinsuranceId); return(View(clientEditViewModel)); }
public IActionResult Edit(string id) { Client client = context.Clients.FindAsync(id).Result; ClientEditViewModel model = new ClientEditViewModel() { Id = client.Id, FirstName = client.FirstName, LastName = client.LastName, Email = client.Email, PhoneNumber = client.PhoneNumber, IsAdult = client.IsAdult }; return(View(model)); }
public ActionResult Edit(ClientEditViewModel viewModel) { // ValidateEmployee(viewModel.Client); if (ModelState.IsValid) { var client = viewModel.Client; _clientRepo.Update(client); TempData["Message"] = "Client was successfully updated!"; return(RedirectToAction("Detail", new { id = client.Id })); } return(View(viewModel)); }
// GET: Clients/Details/5 public async Task <IActionResult> Details(int?id) { if (id == null) { return(NotFound()); } var viewModel = new ClientEditViewModel(); viewModel.ClientAssessments = await _context.ClientAssessments .Include(c => c.Client) .ThenInclude(Client => Client.StatusType) .Include(c => c.Client) .ThenInclude(Client => Client.User) .Include(c => c.Client) .ThenInclude(Client => Client.Facility) .Include(c => c.Assessment) .Include(c => c.Client) .ThenInclude(Client => Client.Goals) .Include(c => c.Client) .ThenInclude(Client => Client.TherapySessions) .Where(c => c.ClientId == id).ToListAsync(); viewModel.Client = await _context.Clients .Include(c => c.StatusType) .Include(c => c.User) .Include(c => c.Facility) .FirstOrDefaultAsync(c => c.ClientId == id); ViewBag.HasAssessment = "true"; ViewBag.HasGoal = "true"; if (viewModel.ClientAssessments.Count == 0) { ViewBag.HasAssessment = "false"; viewModel.Client = await _context.Clients .Include(c => c.StatusType) .Include(c => c.User) .Include(c => c.Facility) .FirstOrDefaultAsync(c => c.ClientId == id); } return(View(viewModel)); }
public async Task <IActionResult> EditProfile() { var model = new ClientEditViewModel(); var user = await _userManager.GetUserAsync(HttpContext.User); var userId = _userManager.GetUserId(HttpContext.User); var username = _userManager.GetUserName(HttpContext.User); if (userId != null) { var client = _clientRepository.GetClientByUserId(userId); model.Provinces = await _autoFillService.AddProvinceListAsync(); model.FirstName = user.FirstName; model.PhoneNumber = user.PhoneNumber; model.LastName = user.LastName; model.ClientID = client.Id; model.CompanyName = client.CompanyName; //model.ContactPerson = client.ContactPerson; model.ClientID = client.Id; model.UserName = username; model.WebsiteUrl = client.WebsiteUrl; model.ContactPerson = client.ContactPerson; //model.PhoneNumber = client.ContactNumber; model.BusinessStreamID = client.BusinessstreamID; PostalCode postalcode = _postalCodeRepository.GetById(client.PostalCodeID); string[] postalcodeArry = postalcode.Code.Split("-"); if (postalcodeArry.Count() > 0) { model.PostalAddrss1 = postalcodeArry[0]; model.PostalAddrss2 = postalcodeArry[1]; } model.ProvinceID = postalcode.ProvinceID; model.Address = client.Address; model.CityName = client.PostalCode.CityName; model.Town = client.PostalCode.Town; //} } return(View(model)); }
public IActionResult Edit(ClientEditViewModel model) { if (ModelState.IsValid) { Client changed = _clientsRepository.GetClient(model.Id); changed.IdNumber1 = model.IdNumber1; changed.IdNumber2 = model.IdNumber2; changed.IdNumber3 = model.IdNumber3; changed.Name = model.Name; changed.RepMail = model.RepMail; changed.RepName = model.RepName; changed.RepPhone = model.RepPhone; changed.Street = model.Street; changed.Zip = model.Zip; _clientsRepository.Update(changed); return(RedirectToAction("details", new { id = model.Id })); } return(RedirectToAction("edit", new { id = model.Id })); }
public async Task <IActionResult> Delete(ClientEditViewModel viewmodel) { var isRecordFound = _dbContext.Clients.Any(o => o.Id == viewmodel.Id); if (ModelState.IsValid && isRecordFound) { var record = _mapper.Map <Client>(viewmodel); _dbContext.Remove(record); var result = await _dbContext.SaveChangesAsync(); if (result > 0) { return(RedirectToAction(nameof(Index))); } ModelState.AddModelError("", "Failed"); } return(View(viewmodel)); }
public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var client = _clientRepo.Get((int)id); if (client == null) { return(HttpNotFound()); } var viewModel = new ClientEditViewModel() { Client = client }; return(View(viewModel)); }
public ViewResult Edit(Guid id) { Client client = _clientsRepository.GetClient(id); ClientEditViewModel model = new ClientEditViewModel { City = client.City, ClientType = client.ClientType, Id = client.Id, IdNumber1 = client.IdNumber1, IdNumber2 = client.IdNumber2, IdNumber3 = client.IdNumber3, Name = client.Name, RepMail = client.RepMail, RepName = client.RepName, RepPhone = client.RepPhone, Street = client.Street, Zip = client.Zip }; return(View(model)); }
// Ação de edição de um cliente específico public ActionResult Edit(int clientId) { //Busca pelo cliente cujo Id tenha sido fornecido como parâmetro var client = _unitOfWork.Clients.SingleOrDefault(c => c.Id == clientId); //Caso não encontre o cliente específico retorna Not Found if (client == null) { return(HttpNotFound()); } //Caso seja encontrado cria uma nova instância de ClientViewModel populada com os dados do cliente. var editViewModel = new ClientEditViewModel { Client = client, CreditLimit = Convert.ToString(client.CreditLimit) }; //Retorna a ClientViewModel para a view ClienteForm(novo cliente ou edição de cliente) return(View("ClientForm", editViewModel)); }
public async Task <ActionResult> Edit(ClientEditViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel).WithError("Client was unable to be saved successfully")); } Client client = Mapper.Map <ClientEditViewModel, Client>(viewModel); if (viewModel.ID > 0) { _clientRepository.Update(client); } else { _clientRepository.Add(client); } await _clientRepository.SaveAsync(); return(RedirectToAction("Index").WithSuccess("Client was saved successfully")); }
//Get: /Client/Edit/0 public async Task <ActionResult> Edit(int id) { ClientEditViewModel viewModel; if (id > 0) //Existing Client { Client client = await _clientRepository.GetByIdForEditAsync(id); if (client == null) { return(HttpNotFound()); } viewModel = Mapper.Map <Client, ClientEditViewModel>(client); } else //New Client { viewModel = new ClientEditViewModel(); } return(View(viewModel)); }
public IActionResult Edit(ClientEditViewModel model) { Client samePhoneNumber = context.Clients.FirstOrDefault(u => u.PhoneNumber == model.PhoneNumber); if (samePhoneNumber != null && samePhoneNumber.Id != model.Id) { ModelState.AddModelError("PhoneNumber", "There is an user with this phone number."); //return Page(); } Client sameEmail = context.Clients.FirstOrDefault(u => u.Email == model.Email); if (sameEmail != null && sameEmail.Id != model.Id) { ModelState.AddModelError("Email", "There is an user with this email."); //return Page(); } if (ModelState.IsValid) { Client client = context.Clients.FindAsync(model.Id).Result; client.FirstName = model.FirstName; client.LastName = model.LastName; client.PhoneNumber = model.PhoneNumber; client.Email = model.Email; client.IsAdult = !model.IsAdult; context.Clients.Update(client); context.SaveChanges(); return(Redirect("~/Client/Details/" + client.Id)); } return(View(model)); }
public async Task <IActionResult> Edit(ClientEditViewModel editModel) { if (ModelState.IsValid) { Client client = new Client() { Id = editModel.Id, Name = editModel.Name, Surname = editModel.Surname, Email = editModel.Email, PhoneNumber = editModel.PhoneNumber, IsAdult = editModel.IsAdult }; try { _context.Update(client); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ClientExists(client.Id)) { return(NotFound()); } else { client.Id = editModel.Id; } } return(RedirectToAction(nameof(Index))); } return(View(editModel)); }
public ClientEmptyState(ClientEditViewModel clientEditViewModel) { this._clientEditViewModel = clientEditViewModel; }
public IActionResult Edit(ClientEditViewModel model) { if (ModelState.IsValid) { string[] validImageTypes = new string[] { "image/gif", "image/jpeg", "image/pjpeg", "image/png" }; // Find existed Client by Id Client client = _context.Set <Client>() .FindBy(c => c.ClientId == new Guid(model.ClientId)) .Include(cl => cl.ClientImages) .FirstOrDefault(); if (client != null) { // Update Client's Properties client.Name = model.Name; client.ShortDescription = model.ShortDescription; client.Description = model.Description; client.HttpUrl = model.HttpUrl; } else { return(NotFound($"Клиент с id: {model.ClientId} не найден")); } //// Check on null or zero length file if (model.ImageUpload != null && model.ImageUpload.Length > 0) { if (validImageTypes.Contains(model.ImageUpload.ContentType)) { // Remove existed File from Server string pathDir = _optionsAccessor.Value.ClientImages; string pathExistedFile = client.ClientImages.FirstOrDefault()?.Path.Substring(1); if (!string.IsNullOrEmpty(pathExistedFile)) { _filesHelper.Delete(pathExistedFile); } // Copy New File to Server string pathNewFileName = Guid.NewGuid().ToString(); string pathNewFileExt = Path.GetExtension(model.ImageUpload.FileName); string pathNewFile = pathDir + pathNewFileName + pathNewFileExt; _filesHelper.Copy(pathDir, pathNewFileName + pathNewFileExt, model.ImageUpload); // SYNC changes to Database ClientImage clientNewImage = new ClientImage { IsPoster = true, Path = @"\" + pathDir + pathNewFileName + pathNewFileExt }; // Find existed image ClientImage clientExistedImage = client.ClientImages.FirstOrDefault(); // Remove previous image if (clientExistedImage != null) { client.ClientImages.Remove(clientExistedImage); } client.ClientImages.Add(clientNewImage); } //// Update DB _context.Set <Client>().Update(client, new Guid(model.ClientId)); return(RedirectToAction("Index")); } else { ModelState.AddModelError("ImageUpload", "Файл пустой или не в формате JPG, GIF или PNG"); } } // If Model has errors return(View(model)); }
public ClientCreationState(ClientEditViewModel clientEditViewModel) { this._clientEditViewModel = clientEditViewModel; }
public void Init() { sqlConnection = new SqlConnection(); var connectionString = @"data source=(LocalDb)\MSSQLLocalDB;initial catalog=Lascarizador.LascarizadorDbContext;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"; sqlBuilder = new SqlConnectionStringBuilder(connectionString); sqlConnection.ConnectionString = sqlBuilder.ConnectionString; _context = new LascarizadorDbContext(sqlConnection); _unitOfWork = new UnitOfWork(_context); clientsController = new ClientsController(); cardsController = new CardsController(); //Cria Cliente clientCPF = "00424704714"; client = new Client { CPF = clientCPF, CreditLimit = Convert.ToDecimal(100.00), Email = "*****@*****.**", Name = "Pedrita Flinstone", Saldo = 0 }; var clientEVM = new ClientEditViewModel { Client = client, CreditLimit = "100,00" }; var clientResult = clientsController.Save(clientEVM); var cardBrandId = Convert.ToByte(1); //bedrock_visa; cardBrandApiName = "bedrock_visa"; var cardType = Convert.ToByte(2); //tarja_magnetica cardPassword = "******"; //Encripta a senha e adiciona o Hash e o Salt ao dados do cartão var securedPassword = new SecuredPassword(cardPassword); var cardEVM = new CardEditViewModel { Card = new Card { CardBrandId = cardBrandId, CardHolderName = "PEDRITA FLINTSTONE", CardTypeId = cardType, Client = client, Cvv = 999, ExpirationDate = DateTime.Parse("2019/01/01"), HashPassword = securedPassword.Hash, HasPassword = true, IsBlocked = false, Number = "5555666677778888", Password = cardPassword, SaltPassword = securedPassword.Hash }, CardBrands = null, CardTypes = null, ClientName = null, ExpirationMonth = 01, ExpirationYear = 2019 }; var cardResult = cardsController.Save(cardEVM); }
public async Task <IActionResult> EditProfile(ClientEditViewModel model) { if (ModelState.IsValid) { var user = _userManager.GetUserAsync(HttpContext.User).Result; model.Provinces = await _autoFillService.AddProvinceListAsync(); int postalId = 0; string postalcode = model.PostalAddrss1 + "-" + model.PostalAddrss2; var postalcodeList = _postalCodeRepository.Find(x => x.Code == postalcode); foreach (var postalcodeobj in postalcodeList) { postalId = postalcodeobj.Id; } Client client = _clientRepository.GetClientByUserId(user.Id); //client.Id = model.ClientID; client.CompanyName = model.CompanyName; client.ContactNumber = model.PhoneNumber; client.ContactPerson = model.ContactPerson; client.WebsiteUrl = model.WebsiteUrl; client.PostalCodeID = postalId; client.Address = model.Address; //client.ApplicationUser = user; if (model.Files != null) { //string webrootpath = _hostingEnvironment.WebRootPath; string folderpath = Path.Combine(_hostingEnvironment.WebRootPath, "assets", "img", "companies", client.Id.ToString()); string virtualPath = Path.Combine("..", "assets", "img", "companies", client.Id.ToString()); if (!Directory.Exists(folderpath)) { Directory.CreateDirectory(folderpath); } string filePath = Path.Combine(folderpath, $"companyimage.png"); string virtualFilePath = Path.Combine(virtualPath, $"companyimage.png"); using (Image img = Image.FromStream(model.Files[0].OpenReadStream())) { var resizedImg = img.Resize(250, 250); resizedImg.SaveIntoDisk(filePath); //save image path into comapnyimage object IEnumerable <CompanyImage> companyImages = await _companyImage.FindByAsyn(x => x.ClientId == model.ClientID); CompanyImage companyImage = new CompanyImage(); if (companyImages.Count() < 1) { companyImage.ImagePath = virtualFilePath; companyImage.Client = client; await _companyImage.AddAsyn(companyImage); } else { companyImage = companyImages.FirstOrDefault(); companyImage.ImagePath = virtualFilePath; _companyImage.Update(companyImage); } } } var result = _clientRepository.Update(client); user.FirstName = model.FirstName; user.LastName = model.LastName; user.PhoneNumber = model.PhoneNumber; // await _companyImage.SaveAsync(); //Saving company image //long size = model.Files.Sum(f => f.Length); //End of company save image if (result > 0) { ModelState.Clear(); ViewData["success"] = "データが保存されました"; } else { //foreach (var error in ModelState) //{ // ModelState.AddModelError(string.Empty, error.Description); //} ViewData["error"] = "データ保存の際にエラーが発生しました"; } } return(View(model)); }
public ClientSearchState(ClientEditViewModel clientEditViewModel) { this._clientEditViewModel = clientEditViewModel; }
// Ação de Salvar dados de Cliente (novo ou edição) public ActionResult Save(ClientEditViewModel clientEditViewModel) { //Caso exista algum problema, cria uma nova instância da ClientEditViewModel para retornar os dados para a view ClientForm var editViewModel = new ClientEditViewModel { Client = clientEditViewModel.Client, CreditLimit = clientEditViewModel.CreditLimit }; //Se o ModelState for válido if (!ModelState.IsValid) { //Retorna a ClienteEditViewModel para a view ClientForm(novo ou edição de cliente) return(View("ClientForm", editViewModel)); } //Verifica se o CPF é um número válido if (!ValidaCPF.IsCpf(clientEditViewModel.Client.CPF)) { //Gera um erro no ModelState ModelState.AddModelError("", "O número de CPF não é válido"); //Retorna a ClienteEditViewModel para a view ClientForm(novo ou edição de cliente) return(View("ClientForm", editViewModel)); } //Verifica CreditLimit está no formato numérico string tempCreditLimit; tempCreditLimit = clientEditViewModel.CreditLimit.Trim(); tempCreditLimit = clientEditViewModel.CreditLimit.Replace(",", ""); if (!tempCreditLimit.All(char.IsDigit)) { //Gera um erro no ModelState ModelState.AddModelError("", "O Campo Limite de Crédito apresenta caracteres inválidos"); //Retorna a ClienteEditViewModel para a view ClientForm(novo ou edição de cliente) return(View("ClientForm", editViewModel)); } decimal dec; bool isDecimal = decimal.TryParse(clientEditViewModel.CreditLimit, out dec); if (!isDecimal) { //Gera um erro no ModelState ModelState.AddModelError("", "O Campo Limite de Crédito apresenta caracteres inválidos"); //Retorna a ClienteEditViewModel para a view ClientForm(novo ou edição de cliente) return(View("ClientForm", editViewModel)); } var decCreditLimit = decimal.Parse(clientEditViewModel.CreditLimit); //Verifica se os dados vem de um novo cliente ou se é uma edição de um cliente existente if (clientEditViewModel.Client.Id == 0) { // Atualiza o Limiti de Crédito com o valor do tipo decimal clientEditViewModel.Client.CreditLimit = decCreditLimit; //Caso seja um novo cliente adiciona ele a base de dados _unitOfWork.Clients.Add(clientEditViewModel.Client); } else { //Caso seja um cliente existente sobrepõe os campos novos com os antigos. var clientInDb = _unitOfWork.Clients.Get(clientEditViewModel.Client.Id); clientInDb.Name = clientEditViewModel.Client.Name; clientInDb.CPF = clientEditViewModel.Client.CPF; clientInDb.CreditLimit = decCreditLimit; clientInDb.Email = clientEditViewModel.Client.Email; } _unitOfWork.Complete(); //Redireciona para a view Index (listagem de clientes) return(RedirectToAction("Index", "Clients")); }
public ClientLoadedState(ClientEditViewModel clientEditViewModel) { this._clientEditViewModel = clientEditViewModel; }