public async Task <IActionResult> Edit(int id, CreateOrUpdateViewModel category) { if (id != category.Id) { return(NotFound()); } if (ModelState.IsValid) { category.Alias = category.Name.ToFriendlyUrl(); category.UpdateDate = DateTime.Now; var viewModel = _mapper.Map <Category>(category); _context.Update(viewModel); Alert("Lưu danh mục thành công!"); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(nameof(CreateOrUpdate), category)); }
private void SetNewAction() { if (RecordEntryViewModel.AllowNewLookup && LookupFormService != null && LookupFormService.GetFormMetadata(RecordTypeToLookup, LookupService) != null && FormService != null && FormService.AllowAddNew(FieldName, GetRecordType())) { NewAction = () => { var formController = new FormController(LookupService, LookupFormService, ApplicationController); var newRecord = LookupService.NewRecord(RecordTypeToLookup); Action onSave = () => { Value = LookupService.ToLookup(newRecord); if (UsePicklist) { var newPicklistItem = new ReferencePicklistItem(newRecord, Value.Name); ItemsSource = ItemsSource .Union(new[] { newPicklistItem }) .OrderBy(r => r.Name) .ToArray(); SelectedItem = newPicklistItem; } SetEnteredTestWithoutClearingValue(Value.Name); RecordEntryViewModel.ClearChildForm(); }; var newForm = new CreateOrUpdateViewModel(newRecord, formController, onSave, RecordEntryViewModel.ClearChildForm); RecordEntryViewModel.LoadChildForm(newForm); }; } else { NewAction = null; } }
//change user prop[erties by those in the viewmodel. public void UpdateUser(User userToUpdate, CreateOrUpdateViewModel vm) { userToUpdate.FirstName = vm.FirstName; userToUpdate.LastName = vm.LastName; userToUpdate.BirthDay = vm.BirthDay; userToUpdate.Email = vm.Email; userToUpdate.Password = vm.Password; }
//create new user, with data from viewmodel. public User CreateNewUserFromViewModel(CreateOrUpdateViewModel vm) { var user = new User() { UserName = vm.UserName }; UpdateUser(user, vm); return(user); }
public async Task <IActionResult> Edit(int id, CreateOrUpdateViewModel createViewModel) { if (id != createViewModel.news.Id) { return(NotFound()); } if (createViewModel.image != null) { string fileName = Path.GetFileName(createViewModel.image.FileName); string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\", fileName); string dbFilePath = Path.Combine("\\images\\", fileName); FileStream fileStream = new FileStream(filePath, FileMode.Create); var pathToDelete = Path.Combine(Environment.CurrentDirectory, "wwwroot\\", "@" + createViewModel.imagePath); using (fileStream) { //Deleting existing file if (System.IO.File.Exists(pathToDelete)) { System.IO.File.Delete(pathToDelete); } //Creating new file await createViewModel.image.CopyToAsync(fileStream); } createViewModel.news.Imagepath = dbFilePath; } createViewModel.news.CreatedOn = DateTime.Now; createViewModel.news.AuthorId = User.FindFirst(ClaimTypes.NameIdentifier).Value; if (ModelState.IsValid) { try { _newsService.Update(createViewModel.news); } catch (DbUpdateConcurrencyException) { if (!NewsExists(createViewModel.news.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["CategoryId"] = new SelectList(_categoryService.GetAll(), "Id", "Name", createViewModel.news.CategoryId); return(View(createViewModel)); }
//view for updating user details. public IActionResult CreateOrUpdate() { var currentUser = _um.GetUser(); if (currentUser != null) { //if not new user, clear password field before showing view. currentUser.Password = null; var vm = new CreateOrUpdateViewModel(currentUser); return(View(vm)); } return(View()); }
public GameRoundParams CreateOrUpdateGame(CreateOrUpdateViewModel model) { var gameParams = _mapper.Map <CreateOrUpdateViewModel, GameParams>(model); _gameService.CreateOrUpdate(gameParams); var gameRoundParams = new GameRoundParams(gameParams.Id); gameRoundParams.Round = gameRoundParams.Id == 0 ? 1 : gameRoundParams.Round; var gameRound = _gameRoundService.CreateOrUpdate(gameRoundParams); _gameService.SendGameCreatedMessage(new Services.Models.GameCreatedModel(gameParams.Id, gameParams.HostUserId, gameParams.GuestUserId, gameRound.Id, gameRound.Round, model.IsBotActivated)); return(gameRoundParams); }
public async Task <IActionResult> CreateOrUpdate(int?id) { var model = new CreateOrUpdateViewModel(); if (id != null) { var data = await _context.Categories.FindAsync(id); model = _mapper.Map <CreateOrUpdateViewModel>(data); if (model == null) { return(NotFound()); } } return(View(model)); }
public async Task <ActionResult> Edit(long?id) { var model = new CreateOrUpdateViewModel(); if (id.HasValue) { model.User = await _userAppService.GetUser(id.Value); } else { model.User = new UserDto(); } model.Roles = await _roleAppService.GetRoleList(); // ViewBag.roles = new SelectItem return(PartialView(model)); }
public IActionResult CreateOrUpdate(CreateOrUpdateViewModel model) { var accessToken = HttpContext.Request.Headers["Authorization"].ToString().GetAccessTokenFromHeaderString(); var loyaltyParams = _mapper.Map <CreateOrUpdateViewModel, LoyaltyParams>(model); var loyalty = _loyaltyService.GetLoyaltyByUserId(accessToken); if (loyalty != null) { loyaltyParams.Id = loyalty.Id; } _loyaltyService.CreateOrUpdate(loyaltyParams); var result = _mapper.Map <LoyaltyParams, CreateOrUpdateViewModel>(loyaltyParams); return(Ok(result)); }
public async Task <IActionResult> CreateOrUpdate(CreateOrUpdateViewModel model) { var accessToken = HttpContext.Request.Headers["Authorization"].ToString().GetAccessTokenFromHeaderString(); var gameRoundParams = _gameManager.CreateOrUpdateGame(model); //If the game has just began, a contact record should be created which indicates they are in contact and can start chat if (gameRoundParams.Round == 1) { await _contactService.SyncContactTable(accessToken, model.HostUserId, model.GuestUserId); } return(Ok(new CreateOrUpdateViewModel( gameRoundParams.GameId, gameRoundParams.Id, gameRoundParams.Round, model.HostUserId, model.GuestUserId, model.Credit))); }
// GET: News/Edit/5 public IActionResult Edit(int?id) { if (id == null) { return(NotFound()); } var result = _newsService.Get(id ?? 1); if (result == null) { return(NotFound()); } var editViewModel = new CreateOrUpdateViewModel() { news = result, imagePath = result.Imagepath }; ViewData["CategoryId"] = new SelectList(_categoryService.GetAll(), "Id", "Name", result.CategoryId); return(View(editViewModel)); }
public async Task <IActionResult> Create(CreateOrUpdateViewModel createViewModel) { if (createViewModel.image != null) { var fileName = Path.GetFileName(createViewModel.image.FileName); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\", fileName); var dbFilePath = Path.Combine("\\images\\", fileName); var fileStream = new FileStream(filePath, FileMode.Create); using (fileStream) { await createViewModel.image.CopyToAsync(fileStream); } createViewModel.news.Imagepath = dbFilePath; } createViewModel.news.CreatedOn = DateTime.Now; createViewModel.news.AuthorId = User.FindFirst(ClaimTypes.NameIdentifier).Value; _newsService.Add(createViewModel.news); return(RedirectToAction(nameof(Index))); }
public void RecreateGrid(bool resetQueryRun = true) { if (RecordType != null) { DynamicGridViewModel = new DynamicGridViewModel(ApplicationController) { PageSize = StandardPageSize, ViewType = ViewType.MainApplicationView, RecordService = RecordService, RecordType = RecordType, IsReadOnly = true, FormController = new FormController(RecordService, null, ApplicationController), GetGridRecords = (b) => GetGridRecords(b), DisplayTotalCount = false, GetTotalCount = GetGridTotalCount, MultiSelect = true, GridLoaded = false, FieldMetadata = ExplicitlySelectedColumns }; var customFunctionList = new List <CustomGridFunction>() { new CustomGridFunction("QUERY", "Run Query", QuickFind), new CustomGridFunction("BACKTOQUERY", "Back To Query", (g) => { ResetToQueryEntry(); }, (g) => !IsQuickFind && QueryRun), new CustomGridFunction("EDITCOLUMNS", "Edit Columns", (g) => LoadColumnEdit(), (g) => DynamicGridViewModel != null), new CustomGridFunction("DISPLAYTOTALS", (g) => g.DisplayTotalCount ? "Hide Totals" : "Display Totals", (g) => { g.DisplayTotalCount = !g.DisplayTotalCount; g.ReloadGrid(); }, (g) => DynamicGridViewModel != null) }; if (FormService != null && AllowCrud) { DynamicGridViewModel.EditRow = (g) => { var formMetadata = FormService.GetFormMetadata(RecordType, RecordService); var formController = new FormController(RecordService, FormService, ApplicationController); var selectedRow = g; if (selectedRow != null) { Action onSave = () => { ClearChildForm(); ClearNotInIds(); DynamicGridViewModel.ReloadGrid(); }; var record = selectedRow.Record; var createOrUpdateRecord = RecordService.Get(record.Type, record.Id); new[] { createOrUpdateRecord }.PopulateEmptyLookups(RecordService, null); var newForm = new CreateOrUpdateViewModel(createOrUpdateRecord, formController, onSave, ClearChildForm); ClearNotInIds(); LoadChildForm(newForm); } }; DynamicGridViewModel.EditRowNew = (g) => { var formMetadata = FormService.GetFormMetadata(RecordType, RecordService); var formController = new FormController(RecordService, FormService, ApplicationController); var selectedRow = g; if (selectedRow != null) { var record = selectedRow.Record; CreateOrUpdateViewModel vmRef = null; var createOrUpdateRecord = RecordService.Get(record.Type, record.Id); new[] { createOrUpdateRecord }.PopulateEmptyLookups(RecordService, null); vmRef = new CreateOrUpdateViewModel(createOrUpdateRecord, formController, () => { vmRef.ValidationPrompt = "Changes Have Been Saved"; ClearNotInIds(); DynamicGridViewModel.ReloadGrid(); }, () => ApplicationController.Remove(vmRef), cancelButtonLabel: "Close"); ApplicationController.NavigateTo(vmRef); //LoadChildForm(newForm); } }; DynamicGridViewModel.AddRow = () => { var formMetadata = FormService.GetFormMetadata(RecordType, RecordService); var formController = new FormController(RecordService, FormService, ApplicationController); Action onSave = () => { ClearChildForm(); ClearNotInIds(); DynamicGridViewModel.ReloadGrid(); }; var newForm = new CreateOrUpdateViewModel(RecordService.NewRecord(RecordType), formController, onSave, ClearChildForm, explicitIsCreate: true); LoadChildForm(newForm); }; } customFunctionList.Add(new CustomGridFunction("DOWNLOAD", "Download", new[] { new CustomGridFunction("DOWNLOADEXCEL", "Excel", (g) => g.DownloadExcel(), (g) => g.GridRecords != null && g.GridRecords.Any()), new CustomGridFunction("DOWNLOADCSV", "CSV", (g) => g.DownloadCsv(), (g) => g.GridRecords != null && g.GridRecords.Any()) })); if (CustomFunctions != null) { foreach (var item in CustomFunctions) { customFunctionList.Add(item); } } DynamicGridViewModel.AddGridButtons(customFunctionList); if (LoadInitially) { DynamicGridViewModel.ReloadGrid(); } RefreshConditionButtons(); RefreshConditionButtons(isNotIn: true); if (resetQueryRun) { QueryRun = false; } } }
//executes the creation of a user and saving it to database. public IActionResult CreateUpdateResult(CreateOrUpdateViewModel vm) { //flag to show in view if saving succeded. ViewBag.Success = true; //flag to show if new user was created, or a pre existed user was just updated. ViewBag.NewUser = true; //this set up an if() that will stop _login view validation to show up //when a guest try to register using this action. TempData["Validation"] = "true"; //get current user. var currentUser = _um.GetUser(); //if user exist, remove username from validation checks. if (currentUser != null) { ModelState.Remove("UserName"); } //returns to CreateOrUpdate view if form was not completed. if (!ModelState.IsValid) { //check each property, on faild validation create Tempdata with the propery name //as the key. foreach (var item in ModelState.Keys) { if (ModelState.GetValidationState(item) == ModelValidationState.Invalid) { //this will be used to check which properties failed validation //ad a span with red asterisk will be created in the view besides the //relevent input element. TempData[item] = "Show*"; } } return(View("CreateOrUpdate", vm)); } //Create or update User in db. if (currentUser != null) { //Updating an existing user. ViewBag.NewUser = false; var userToUpdate = _db.UserRepository.Get(currentUser.Id); //encrypts the new password. vm.Password = EncryptionHelper.ComputeHash(vm.Password, "SHA512", null); _um.UpdateUser(userToUpdate, vm); //tries to save data to database. if (!_db.Save()) { //if failed in saving, show that in the view. ViewBag.Success = false; } } else { //creats a User class from the viewmodel sent in the form. var user = _um.CreateNewUserFromViewModel(vm); //encrypts the password. user.Password = EncryptionHelper.ComputeHash(user.Password, "SHA512", null); //tires to save user in the database. if (!_db.UserRepository.Create(user)) { //if failed in saving, show that in the view. ViewBag.Success = false; } else { //Creatin a new user. ViewBag.NewUser = true; //after saving, create a new log entry in the database. _um.CreateCurrentUserCookie(user); LogEntry entry = new LogEntry() { Content = $"user: {user.UserName} created", TimeStamp = DateTime.Now }; _db.LogEntryRepository.Create(entry); } } return(View(vm)); }
public void RecreateGrid() { if (RecordType != null) { DynamicGridViewModel = new DynamicGridViewModel(ApplicationController) { PageSize = StandardPageSize, ViewType = ViewType.MainApplicationView, RecordService = RecordService, RecordType = RecordType, IsReadOnly = true, FormController = new FormController(RecordService, null, ApplicationController), GetGridRecords = GetGridRecords, MultiSelect = true, GridLoaded = false }; var customFunctionList = new List <CustomGridFunction>() { new CustomGridFunction("QUERY", "Run Query", QuickFind) }; if (FormService != null) { DynamicGridViewModel.EditRow = (g) => { var formMetadata = FormService.GetFormMetadata(RecordType, RecordService); var formController = new FormController(this.RecordService, FormService, ApplicationController); var selectedRow = g; if (selectedRow != null) { Action onSave = () => { ClearChildForm(); DynamicGridViewModel.ReloadGrid(); }; var record = selectedRow.Record; var newForm = new CreateOrUpdateViewModel(RecordService.Get(record.Type, record.Id), formController, onSave, ClearChildForm); LoadChildForm(newForm); } }; DynamicGridViewModel.AddRow = () => { var formMetadata = FormService.GetFormMetadata(RecordType, RecordService); var formController = new FormController(RecordService, FormService, ApplicationController); Action onSave = () => { ClearChildForm(); DynamicGridViewModel.ReloadGrid(); }; var newForm = new CreateOrUpdateViewModel(RecordService.NewRecord(RecordType), formController, onSave, ClearChildForm, explicitIsCreate: true); LoadChildForm(newForm); }; } customFunctionList.Add(new CustomGridFunction("CSV", "Download CSV", (g) => g.DownloadCsv(), (g) => g.GridRecords != null && g.GridRecords.Any())); if (CustomFunctions != null) { foreach (var item in CustomFunctions) { customFunctionList.Add(item); } } DynamicGridViewModel.AddGridButtons(customFunctionList); if (LoadInitially) { DynamicGridViewModel.ReloadGrid(); } RefreshConditionButtons(); } }
private void RecreateGrid() { if (DynamicGridViewModel != null) { Controller.RemoveFromUi(DynamicGridViewModel); } try { //okay lets somehow load the results for this row into a crud dialog view //which loads a dynamic grid - similar to query but no query - DynamicGridViewModel = new DynamicGridViewModel(ApplicationController) { PageSize = 25, RecordService = RecordService, RecordType = SummaryItem.RecordTypeSchemaName, IsReadOnly = true, FormController = new FormController(RecordService, null, ApplicationController), GetGridRecords = (b) => { return(DynamicGridViewModel.GetGridRecord(GetAllTheseRecords(), b)); }, DisplayTotalCount = true, GetTotalCount = () => GetAllTheseRecords().Count(), MultiSelect = true, GridLoaded = false, FieldMetadata = ExplicitlySelectedColumns }; var customFunctionList = new List <CustomGridFunction>() { new CustomGridFunction("BACKTOSUMMARY", "Back To Summary", Remove), new CustomGridFunction("EDITCOLUMNS", "Edit Columns", (g) => LoadColumnEdit(), (g) => DynamicGridViewModel != null), new CustomGridFunction("DOWNLOAD", "Download", new[] { new CustomGridFunction("DOWNLOADEXCEL", "Excel", (g) => g.DownloadExcel(), (g) => g.GridRecords != null && g.GridRecords.Any()), new CustomGridFunction("DOWNLOADCSV", "CSV", (g) => g.DownloadCsv(), (g) => g.GridRecords != null && g.GridRecords.Any()) }), new CustomGridFunction("REPLACE", "Bulk Replace", new [] { new CustomGridFunction("BULKREPLACESELECTED", "Selected Only", (g) => { TriggerBulkReplace(true); }, (g) => g.SelectedRows.Any()), new CustomGridFunction("BULKREPLACEALL", "All Results", (g) => { TriggerBulkReplace(false); }, (g) => g.GridRecords != null && g.GridRecords.Any()), }) }; var formService = RecordService.GetFormService() as FormServiceBase; if (formService != null) { DynamicGridViewModel.EditRow = (g) => { var formMetadata = formService.GetFormMetadata(SummaryItem.RecordTypeSchemaName, RecordService); var formController = new FormController(RecordService, formService, ApplicationController); var selectedRow = g; if (selectedRow != null) { Action onSave = () => { ClearChildForm(); _cachedRecords = null; DynamicGridViewModel.ReloadGrid(); }; var record = selectedRow.Record; var newForm = new CreateOrUpdateViewModel(RecordService.Get(record.Type, record.Id), formController, onSave, ClearChildForm); LoadChildForm(newForm); } }; } DynamicGridViewModel.AddGridButtons(customFunctionList); DynamicGridViewModel.ReloadGrid(); Controller.LoadToUi(DynamicGridViewModel); } catch (Exception ex) { ApplicationController.ThrowException(ex); } }