Esempio n. 1
0
        public async Task <IActionResult> Create([Bind("CategoryId,Title,Content,Keyword,Slug,CoverUrl,Status")] PostCategory category)
        {
            if (ModelState["Slug"].ValidationState == ModelValidationState.Invalid || string.IsNullOrEmpty(category.Slug))
            {
                category.Slug = string.IsNullOrEmpty(category.Slug) ? Utils.GenerateSlug(category.Title) : category.Slug;
                ModelState.SetModelValue("Slug", new ValueProviderResult(category.Slug));
                ModelState.Clear();
                TryValidateModel(category);
            }

            if (await _postService.IsSlugCategoryExisted(category.Slug))
            {
                ModelState.AddModelError(nameof(category.Slug), "Đường dẫn đã tồn tại");
            }

            if (ModelState.IsValid)
            {
                await _postService.AddCategoryToDb(category);

                return(RedirectToAction(nameof(Index)));
            }

            var listcategory = await _postService.GetAllCategory();

            listcategory.Insert(0, new PostCategory()
            {
                Title      = "Không có danh mục cha",
                CategoryId = -1
            });
            return(View(category));
        }