public ActionResult Create(PostCreateViewModel model) { if (!ModelState.IsValid) { return(View()); } string fileName = Path.GetFileNameWithoutExtension(model.ImageFile.FileName); string extension = Path.GetExtension(model.ImageFile.FileName); fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; model.postImageURL = "~/img/" + fileName; fileName = Path.Combine(Server.MapPath("~/img/"), fileName); model.ImageFile.SaveAs(fileName); Post newPost = new Post() { postContent = model.postContent, postDate = model.postDate, postDescription = model.postDescription, postImageURL = model.postImageURL }; user = UserManager.FindById(User.Identity.GetUserId()); newPost.CurrentUserId = user.Id; repository.Add(newPost); repository.SaveChanges(); ModelState.Clear(); return(RedirectToAction("List")); }
/// <summary> /// Build <see cref="PostCreateViewModel"/> based on PostType. /// </summary> /// <param name="postType">PostType to load base data for Post.</param> /// <returns>A <see cref="PostCreateViewModel"/> populated with base data.</returns> public async Task <PostCreateViewModel> BuildCreateViewModelAsync( string postType ) { var postTypeRes = await _postTypeService.GetBySlugAsync(postType); if (postTypeRes == null) { throw new NullReferenceException(nameof(PostType)); } var model = new PostCreateViewModel { Status = PostStatus.Draft, //PostTypeTitle = postTypeRes.Title, PostTypeSlug = postTypeRes.Slug, PostTypeId = postTypeRes.Id, PublishDateModel = new PersianDateViewModel() }; await setBaseDataAsync(model); model.CategorySelectList = await _categoryProvider .GetSelectListAsync(postTypeRes.Id, model.LangId); return(await Task.FromResult(model)); }
public async Task <ActionResult> Create(PostCreateViewModel model) { _logger.Info("Creating Post! Params: " + model.ToJson()); if (!ModelState.IsValid) { _logger.Error("Creating Post Form Invalid! Errors: " + ModelState.ToJson()); return(Json(ModelState.ToDictionary())); } if (!await _themesManager.Exists(model.ThemeId)) { ModelState.AddModelError("ThemeId", "Темата не съществува!"); _logger.Error("Creating Post Form Invalid! Errors: " + ModelState.ToJson()); return(Json(ModelState.ToDictionary())); } try { var post = await _postsManager.Create(model, User.Identity.GetUserId()); _logger.Info("Post created successfully!"); return(Json(post)); } catch (Exception ex) { _logger.Error(ex, "Post Creationg Failed!"); throw; } }
// GET: Post/Create public ActionResult Create(int channelId) { var Model = new PostCreateViewModel(); Model.Channel = channelId; return(View(Model)); }
public async Task <int> Create(PostCreateViewModel viewModel) { StringBuilder permalinkBuilder = new StringBuilder(); Post post = new Post(); permalinkBuilder.Append(PermalinkHelper.GenerateSlug(viewModel.Title)); int countPermalinks = _postRepository.GetPermalinks(permalinkBuilder.ToString()); if (countPermalinks > 0) { permalinkBuilder.Append($"-{countPermalinks}"); } post.Permalink = permalinkBuilder.ToString(); post.Title = viewModel.Title; post.Text = viewModel.Text; post.Summary = SummaryHelper.GetWords(viewModel.Text, numberOfWords); post.DatePublished = viewModel.DatePublished; post.DateUpdated = DateTime.Now; post.ImageBase64 = viewModel.ImageBase64; await _postRepository.Save(post); return(post.Id); }
public IActionResult Edit(int id) { var post = _context.Posts.Find(id); var viewModel = new PostCreateViewModel { Categories = _context.Categories.ToList(), Tags = _context.Tags.ToList(), Id = post.Id, Name = post.Name, Slug = post.Slug, Content = post.Content, PostStatus = post.PostStatus, Post = _context.Posts .Include(p => p.PostCategories).Include(pc => pc.PostTags) .FirstOrDefault(p => p.Id == id), SelectedCategory = post.PostCategories.Select(pc => pc.CategoryId).ToList(), SelectedTag = post.PostTags.Select(pt => pt.TagId).ToList(), }; ViewBag.Categories = new SelectList(_context.Categories, "Id", "Name"); ViewBag.Tags = new SelectList(_context.Tags, "Id", "Name"); if (viewModel.Post == null) { return(View("NotFound")); } return(View(viewModel)); }
public async Task <bool> BindModelAsync(ModelBindingContext bindingContext) { object entityName = ""; if (!context.Value.RouteData.Values.TryGetValue("entityName", out entityName)) { return(false); } var type = DebbyAdmin.Entities.FirstOrDefault(t => t.Name == (string)entityName); if (type == null) { return(false); } var entity = entityService.GetEntity((string)entityName); var postCreateViewModel = new PostCreateViewModel(); postCreateViewModel.EntityName = entity.Name; foreach (var prop in entity.Properties) { postCreateViewModel.Data.Add(prop.Name, await bindingContext.ValueProvider.GetValueAsync(prop.Name)); } bindingContext.Model = postCreateViewModel; return(true); }
public ActionResult Create() { PostCreateViewModel postCreateViewModel = new PostCreateViewModel(); postCreateViewModel.Categories = _categoryRepository.Categories.ToList(); return(View(postCreateViewModel)); }
public async Task <IActionResult> Create(PostCreateViewModel model) { if (ModelState.IsValid) { string uniqueFileName = null; if (model.Post != null) { string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images"); uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Post.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { model.Post.CopyTo(fileStream); } } curUser = await userManager.GetEmailAsync(await userManager.GetUserAsync(User)); Post post = new Post { PostPath = uniqueFileName, Caption = model.Caption, AppUser = curUser }; var wait = (model.UploadTime - DateTime.Now).TotalMilliseconds; if (wait >= 0) { BackgroundJob.Schedule(() => UploadPhoto(post), TimeSpan.FromMilliseconds(wait)); } return(RedirectToAction("Profile", "Account")); } return(View()); }
public IActionResult Create(PostCreateViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; var course = _courseService.GetCourseById(new Guid(model.Course)); var employee = _employeeService.GetEmployeeByBaseId( new Guid(_userManager.GetUserId(User)) ); if (ModelState.IsValid) { var post = new Post { Title = model.Title, Content = model.Content, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, Course = course, Owner = employee }; _postService.CreatePost(post); return(RedirectToAction("Index")); } model.CourseList = new SelectList(_employeeService.GetOwnedCourses(employee), "Id", "Title"); return(View(model)); }
public async Task <IActionResult> Create([Bind("Id,Title,ContentPost,MetaDescription,Status,Note,HinhAnh,CategoryId")] PostCreateViewModel post) { if (!ModelState.IsValid) { string uniqueFileName = ProcessUploadedFileC(post); post.MetaTitle = XuLyChuoi.GetMetaTitle(post.Title); post.CreatedDate = DateTime.Now; post.CreatedBy = HttpContext.Session.GetString("UserName"); Post post_1 = new Post { Title = post.Title, ContentPost = post.ContentPost, MetaTitle = post.MetaTitle, CreatedDate = post.CreatedDate, CreatedBy = post.CreatedBy, Status = post.Status, CategoryId = post.CategoryId, MetaDescription = post.MetaDescription, Note = post.Note, HinhAnh = @"/uploads_admin/" + uniqueFileName }; _context.Add(post_1); await _context.SaveChangesAsync(); return(RedirectToAction("Details", new { id = post_1.Id })); // return RedirectToAction(nameof(Index)); } ViewData["CategoryId"] = new SelectList(_context.CategoryPosts, "Id", "CategoryName", post.CategoryId); return(View(post)); }
public IActionResult CreatePost(PostCreateViewModel new_post) { if (ModelState.IsValid) { string uniqFileName = null; if (new_post.Img!=null) { string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "img"); uniqFileName = Guid.NewGuid().ToString() + "_" + new_post.Img.FileName; string filePath = Path.Combine(uploadsFolder, uniqFileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { new_post.Img.CopyTo(fileStream); } } else { uniqFileName = "news.svg"; } var post = new BlogModel() { Name = new_post.Name, Author = new_post.Author, PrewText = new_post.PrewText, FullText = new_post.FullText, Img = uniqFileName }; _blogRepository.CreatePost(post); return RedirectToRoute( new { controller = "Blog", action = "Post", Id=post.Id }); } return View(); }
public IActionResult CreatePost(PostCreateViewModel model) { if (ModelState.IsValid) { string uniqFileName = null; if (model.img != null) { string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "img"); uniqFileName = Guid.NewGuid().ToString() + "_" + model.img.FileName; string filePath = Path.Combine(uploadsFolder, uniqFileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { model.img.CopyTo(fileStream); } } SportsViewModel newPost = new SportsViewModel { name = model.name, description = model.description, price = model.price, img = uniqFileName }; _postRep.CreatePost(newPost); return(RedirectToRoute(new { controller = "SportGoods", action = "SportGood", id = newPost.id })); } return(View()); }
public ActionResult Edit(int id) { if (id == 0) { return(HttpNotFound()); } var tmp = service.Get(id); PostCreateViewModel model = new PostCreateViewModel() { Author = tmp.Author, AuthorId = tmp.AuthorId, Category = tmp.Category, CategoryId = tmp.CategoryId, Content = tmp.Content, Description = tmp.Description, PostId = tmp.PostId, PostImage = tmp.PostImage, PublishedDate = tmp.PublishedDate, SendDate = tmp.SendDate, Slug = tmp.Slug, TagId = tmp.TagId, Title = tmp.Title, VisitCount = tmp.VisitCount }; return(View("Create", model)); }
public async Task <IActionResult> Store(PostCreateViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var identity = (ClaimsIdentity)this.User.Identity; var claim = identity.FindFirst(ClaimTypes.NameIdentifier); var slug = model.Post.Title.ToLower(); slug = Regex.Replace(slug, @"[^a-z0-9\s-]", ""); slug = Regex.Replace(slug, @"\s+", " ").Trim(); slug = Regex.Replace(slug, @"\s", "-"); model.Post.UserID = claim.Value; model.Post.CreatedAt = DateTime.Now; model.Post.Slug = slug; try { _context.Posts.Add(model.Post); await _context.SaveChangesAsync(); } catch (Exception e) { ModelState.AddModelError("", e + ": An error occurred."); } return(RedirectToAction(nameof(Index))); }
public async Task <IActionResult> Create(PostCreateViewModel model) { var userId = userManager.GetUserId(HttpContext.User); var user = userManager.FindByIdAsync(userId).Result; var newPost = new Post { Title = model.Title, Description = CreateDescription(model.Description), Content = model.Content, User = user, CategoryId = model.CategoryId, ImagePath = await Unit.UploadPostMainImageAndGetPathAsync(model.Image, appEnvironment) }; await SetPostTagsAsync(GetTags(model.Tags), newPost); var defaultRating = new Rating { Post = newPost, User = user, Value = 5 }; await db.Ratings.AddAsync(defaultRating); newPost.Rating = defaultRating.Value; await db.Posts.AddAsync(newPost); await db.SaveChangesAsync(); return(RedirectToAction("Index", "Home")); }
public async Task <IActionResult> Create(PostCreateViewModel viewModel) { if (ModelState.IsValid) { var model = _map.Map <Post>(viewModel); model.UserId = _userManager.GetUserId(HttpContext.User); if (viewModel.Photo != null) { var path = "/Files/" + viewModel.Photo.FileName; using (var fileStream = new FileStream(_environment.WebRootPath + path, FileMode.Create)) { viewModel.Photo.CopyTo(fileStream); } model.PhotoPath = path; } var createdPost = await _uow.PostRepository.CreateAsync(model); await _uow.Save(); return(RedirectToAction("Index")); } return(View(viewModel)); }
public async Task <IActionResult> AddPost(PostCreateViewModel createPostViewModel) { if (ModelState.IsValid) { var slug = BlogUtils.CreateSlug(createPostViewModel.Slug); if (string.IsNullOrEmpty(slug)) { ModelState.AddModelError(ModelStateErrorMsgKey, MsgInvalidSlug); return(View(createPostViewModel)); } var slugIsUnique = await _postRepo.CheckIfSlugIsUnique(slug); if (!slugIsUnique) { ModelState.AddModelError(ModelStateErrorMsgKey, MsgDuplicateSlug); return(View(createPostViewModel)); } createPostViewModel.Slug = slug; var user = await GetLoggedInUser(); var result = await _postRepo.AddPost(createPostViewModel, user); if (result) { return(Redirect(Url.Action("AnyPost", "Blog", new { slug }))); } } ModelState.AddModelError(ModelStateErrorMsgKey, MsgSomethingIsWrong); return(View(createPostViewModel)); }
public IActionResult CreatePost(PostCreateViewModel model) { if (ModelState.IsValid) { string uniqFileName = null; if (model.img != null) { string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images"); uniqFileName = Guid.NewGuid().ToString() + "_" + model.img.FileName; string filePath = Path.Combine(uploadsFolder, uniqFileName); model.img.CopyTo(new FileStream(filePath, FileMode.Create)); } else { uniqFileName = "no.png"; } BlogModel newPost = new BlogModel { author = model.author, title = model.title, preview = model.preview, fullPost = model.fullPost, img = uniqFileName }; _postRep.CreatePost(newPost); return(RedirectToRoute("default", new { controller = "Blog", action = "Index" })); } return(View()); }
public ActionResult Edit(int id) { //making a new post var post = new Post(); //getting current user int userId = GetCurrentUserProfileId(); //getting the post by user post = _postRepository.GetUserPostById(id, userId); //list of categories var categories = _categoryRepository.GetAll(); //reusing the post create view model PostCreateViewModel vm = new PostCreateViewModel { //this is popluating the form Post = post, //populating the categories CategoryOptions = categories }; //if post is null or if the user profile dosen't match then you can't edit if (post == null || post.UserProfileId != int.Parse(User.Claims.ElementAt(0).Value)) { return(NotFound()); } else { //otherwise it will return the view model return(View(vm)); } }
public IActionResult Create(PostCreateViewModel model) { var uploadResult = _fileService.Upload(model.PrimaryPicture, "Post", 1024 * 500); var serviceResult = new ServiceResult(); if (uploadResult.IsSuccess) { serviceResult = _adminService.CreatePost(model.ToDto(uploadResult.Data)); if (serviceResult.IsSuccess) { Swal(true, "یک پست با موفقیت اضافه شد"); return(RedirectToAction(nameof(Create))); } } else { serviceResult.Errors = uploadResult.Errors; serviceResult.IsSuccess = false; } AddErrors(serviceResult); return(View(model)); }
public async void Post([FromBody] PostCreateViewModel model) { model.User = await _manager.GetUserAsync(User); //model.User = await _manager.FindByEmailAsync("*****@*****.**"); _postService.Create(model); }
public async Task <IActionResult> Create(PostCreateViewModel post) { post.Communities = GetCommunityDropdown(); try { if (!ModelState.IsValid) { return(View(post)); } var user = await _userManager.FindByNameAsync(User.Identity.Name); var newPost = new Post() { Title = post.Title, Body = post.Body, CommunityId = int.Parse(post.CommunityId), CreatedAt = DateTime.Now, CreatedBy = user.Id, }; _postService.Add(newPost); return(RedirectToAction("Index", "Home")); } catch (Exception ex) { return(View(post)); } }
public ActionResult Edit(int id) { var vm = new PostCreateViewModel(); vm.CategoryOptions = _categoryRepository.GetAll(); var post = _postRepository.GetPostById(id); int userId = GetCurrentUserProfileId(); vm.Post = post; if (post == null) { return(RedirectToAction("Index")); } int currentUserId = GetCurrentUserProfileId(); string UsersRole = GetCurrentUserRole(); if (UsersRole == "Author" && post.UserProfileId != currentUserId) { return(RedirectToAction("Index")); } return(View(vm)); }
public IActionResult Create() { var vm = new PostCreateViewModel(); vm.CategoryOptions = _categoryRepository.GetAll(); return(View(vm)); }
public async Task <ActionResult <PostCreateViewModel> > PostPost(PostCreateViewModel model) { var post = new Post() { UserId = model.UserId, Title = model.Title, Slug = model.Slug, Summary = model.Summary, Body = model.Body, IsPublished = model.IsPublished, PostedAt = DateTime.Now }; _context.Posts.Add(post); foreach (var t in model.Tags) { var postTag = new PostTag() { PostId = post.Id, TagId = t }; _context.PostTags.Add(postTag); } await _context.SaveChangesAsync(); return(model); }
/// <summary> /// Set base collection's data for <see cref="PostCreateViewModel"/> model. /// </summary> /// <param name="model"></param> private async Task setBaseDataAsync(PostCreateViewModel model) { int?langId = null; if (model.LangId > 0) { langId = model.LangId; } model.LanguageSelectList = await _languageViewModelProvider .GetSelectListAsync(langId); if (!langId.HasValue) { model.LangId = int.Parse(model.LanguageSelectList[0].Value); } int?categoryId = null; if (model.CategoryId > 0) { categoryId = model.CategoryId; } model.CategorySelectList = await _categoryProvider .GetSelectListAsync( model.PostTypeId, model.LangId, selectedCategoryId : categoryId ); var tags = await _tagService.LoadAsync(); model.TagsSource = tags.GetTagsAsString(); }
public async Task <IActionResult> Create(PostCreateViewModel post) { if (ModelState.IsValid) { Post postModel = new Post(); postModel.Title = post.Title; postModel.Content = post.Content; postModel.PostDate = DateTime.Now; if (post.Image.FileName != null) { postModel.ImageMimeType = post.Image.ContentType; if (post.Image.Length > 0) //Convert Image to byte and save to database { byte[] imageBytes = null; using (var fileStream = post.Image.OpenReadStream()) using (var memoryStream = new MemoryStream()) { fileStream.CopyTo(memoryStream); imageBytes = memoryStream.ToArray(); } postModel.Image = imageBytes; } } _context.Add(postModel); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(post)); }
public async Task <IActionResult> UpdatePost(PostCreateViewModel model) { var result = await _postService.UpdatePost(model.PostInfo); if (result.IsSuccessStatusCode) { model.PostDetail.PostFid = Convert.ToInt64(result.ResponseData); model.PostDetail.LanguageFid = model.LanguageId; model.PostDetail.FriendlyUrl = GetPostDetailFriendlyUrl(model.PostInfo); await CheckAndUploadFileStream(model, result.ResponseData); if (model.PostDetail.Id == 0) { model.PostDetail.FriendlyUrl = model.FriendlyUrl; result = await _postService.CreateNewPostDetail(model.PostDetail); } else { result = await _postService.UpdatePostDetail(model.PostDetail); } return(Success(model.PostDetail.PostFid)); } return(Error(result.Message)); }
public async Task <ActionResult> Create([FromForm] PostCreateViewModel postVM) { if (ModelState.IsValid) { var uploadedImage = ""; string defaultPostPhoto = ""; if (postVM.PostPhoto != null) { uploadedImage = await ProcessPhoto(postVM.PostPhoto); } try { var post = _mapper.Map <Post>(postVM); post.CreatedAt = DateTime.Now; if (post.CategoryId == 1) { defaultPostPhoto = "sportsPhoto.jpg"; } else if (post.CategoryId == 3) { defaultPostPhoto = "careerPhoto.jpg"; } else if (post.CategoryId == 4) { defaultPostPhoto = "politicsPhoto.jpg"; } else { defaultPostPhoto = "marriagePhoto.jpg"; } post.TitleImageUrl = string.IsNullOrWhiteSpace(uploadedImage) ? defaultPostPhoto : uploadedImage; if (await _postRepo.AddPost(post)) { TempData["Alert"] = "Post Created Successfully"; if (post.Published) { await SendEmailToSuscribers(post); } return(RedirectToAction(nameof(Index))); } ViewBag.Error = "Unable to add post, please try again or contact administrator"; return(View()); } catch (Exception ex) { ViewBag.Error = "Unable to add post, please try again or contact administrator"; return(View()); } } ViewBag.Error = "Please correct the error(s) in Form"; return(View(postVM)); }