public async Task <IActionResult> Edit(int Id) { var staticView = db.StaticViews.Find(Id); if (staticView == null) { HttpContext.Items["ErrorMessage"] = "Не удалось найти представление для изменения."; return(RedirectToAction("Index")); } EditStaticViewModel model = new EditStaticViewModel { Content = ReadFromFile(staticView.Path), Id = staticView.Id, Name = staticView.Name, Route = staticView.Route }; return(View(model)); }
public async Task <IActionResult> Edit(EditStaticViewModel model) { if (!ModelState.IsValid) { return(View(model)); } string routeEnd = model.Route.Split('/').Last(); if (string.IsNullOrWhiteSpace(routeEnd)) { ModelState.AddModelError("Route", "Не указано имя файла. (Имя файла = последнее слово маршрута не считая \"/\")."); return(View(model)); } StaticView view = db.StaticViews.FirstOrDefault(x => x.Id == model.Id); if (view == null) { _logger.LogDebug("Cannot find static view with id = {id}", model.Id); HttpContext.Items["ErrorMessage"] = "Указанная, для редактирования, статическая страница не найдена"; return(RedirectToAction("Index")); } _logger.LogDebug("Edit static view action started with model = {@model}", model); _logger.LogDebug("Check new file location"); FileInfo staticView = new FileInfo(_environment.ContentRootPath + $"/Generic/{model.Route}.cshtml"); if (view.Path != $"/Generic/{model.Route}.html") { if (staticView.Exists) { ModelState.AddModelError("Route", "Данный файл уже существует и не может быть переписан"); return(View(model)); } _logger.LogDebug("Old and new location doesn't match. Create new file"); string[] dirs = model.Route.Split('/'); if (dirs.Length > 1) { string fullPath = _environment.ContentRootPath + "/Generic/"; for (int i = 0; i < dirs.Length - 1; i++) { fullPath += (dirs[i] + "/"); if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } } } staticView.Create(); _logger.LogDebug("Delete old file"); FileInfo oldView = new FileInfo(view.Path); if (oldView.Exists) { oldView.Delete(); } } _logger.LogDebug("Try to write new content to the file"); if (WriteToFile(model.Content, staticView.FullName)) { view.Name = model.Name; view.Path = $"/Generic/{model.Route}.cshtml"; view.Route = model.Route; _logger.LogDebug("Success writing to file. Update the view"); db.StaticViews.Update(view); await db.SaveChangesAsync(); _logger.LogDebug("Successfull update the static view"); HttpContext.Items["SuccessMessage"] = "Обновление статичной страницы успешно!"; } else { HttpContext.Items["ErrorMessage"] = "Не удалось создать файл статической страницы, проверьте ваши права доступа"; } return(RedirectToAction("Index")); }