public ActionResult Add(string slug, AddEditBlogViewModel formData) { if (!ModelState.IsValid) { return(View()); } if (formData.FileUpload != null) { var fileExtension = Path.GetExtension(formData.FileUpload.FileName).ToLower(); if (!AllowedExtenions.Contains(fileExtension)) { ModelState.AddModelError("", "File extension is not allowed"); return(View()); } } var userId = User.Identity.GetUserId(); string str = formData.Title.ToLower(); str = str.Replace("-", " "); str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); str = Regex.Replace(str, @"\s+", " ").Trim(); str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim(); str = Regex.Replace(str, @"\s", "-"); var blog = new Blog(); blog.UserId = userId; blog.Body = formData.Body; blog.Title = formData.Title; blog.Slug = str; blog.Published = formData.Published; blog.MediaUrl = UploadFile(formData.FileUpload); DbContext.Blogs.Add(blog); DbContext.SaveChanges(); return(RedirectToAction(nameof(BlogController.Index))); }
public ActionResult Edit(int?id, AddEditBlogViewModel model) { if (!id.HasValue) { return(RedirectToAction(nameof(BlogController.Index))); } if (!ModelState.IsValid) { return(View()); } if (model.FileUpload != null) { var fileExtension = Path.GetExtension(model.FileUpload.FileName).ToLower(); if (!AllowedExtenions.Contains(fileExtension)) { ModelState.AddModelError("", "File extension is not allowed"); return(View()); } } var blog = DbContext.Blogs.FirstOrDefault(p => p.Id == id.Value); blog.Published = model.Published; blog.Title = model.Title; blog.Body = model.Body; blog.DateUpdated = DateTime.Now; if (model.FileUpload != null) { blog.MediaUrl = UploadFile(model.FileUpload); } DbContext.SaveChanges(); return(RedirectToAction(nameof(BlogController.Index))); }
public ActionResult Edit(int?id) { if (!id.HasValue) { return(RedirectToAction(nameof(BlogController.Index))); } var blog = DbContext.Blogs.FirstOrDefault(p => p.Id == id.Value); if (blog == null) { return(RedirectToAction(nameof(BlogController.Index))); } var model = new AddEditBlogViewModel(); model.Body = blog.Body; model.MedialUrl = blog.MediaUrl; model.Title = blog.Title; model.Published = blog.Published; return(View(model)); }