Ejemplo n.º 1
0
        public async Task <IActionResult> Create([Bind("Title,Description,Slug,Content,Keyword,CoverUrl,Status,CategoryId")] Post post)
        {
            post.DateCreated = DateTime.Now;
            post.AuthorId    = _userManager.GetUserAsync(User).Result.Id;

            if (ModelState["Slug"].ValidationState == ModelValidationState.Invalid || string.IsNullOrEmpty(post.Slug))
            {
                post.Slug = string.IsNullOrEmpty(post.Slug) ? Utils.GenerateSlug(post.Title) : post.Slug;
                ModelState.SetModelValue("Slug", new ValueProviderResult(post.Slug));
                ModelState.Clear();
                TryValidateModel(post);
            }
            if (await _postService.IsSlugPostExisted(post.Slug))
            {
                ModelState.AddModelError(nameof(post.Slug), "Đường dẫn đã tồn tại");
            }

            if (ModelState.IsValid)
            {
                await _postService.AddPostToDb(post);

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CategoryId"] = new SelectList(await _postService.GetAllCategory(), "CategoryId", "Title", post.CategoryId);
            return(View(post));
        }