public ActionResult Create(CategoryViewModel category)
        {
            var dto = category.ToDTO();
            categoryService.Create(dto);

            return RedirectToAction("List");
        }
 public CategoryInfoEditor()
 {
     this.InitializeComponent();
     TiltEffect.SetIsTiltEnabled(this, true);
     this.CategoryVM = ViewModelLocator.CategoryViewModel;
     this.InitializeAppBar();
 }
        public ActionResult Create(CategoryViewModel model)
        {
            if (ModelState.IsValid)
            {
                var categoryDb = this.Mapper.Map<Category>(model);
                this.categories.Add(categoryDb);
                this.categories.SaveChanges();

                if(model.SubCategoryNames != null && model.SubCategoryNames.Count > 0)
                {
                    var subCategories = this.subCategories.All().ToList();
                    foreach (var subCategory in subCategories)
                    {
                        if (model.SubCategoryNames.Contains(subCategory.Name))
                        {
                            categoryDb.SubCategories.Add(subCategory);
                        }
                    }
                }

                this.categories.SaveChanges();

                this.HttpContext.Cache.Remove("menu");
            }

            return RedirectToAction("Index");
        }
 public ActionResult Create(CategoryViewModel model)
 {
     if (ModelState.IsValid)
     {
         categoryService.Create(model);
         return RedirectToAction("List", "Category");
     }
     return View(model);
 }
        public ActionResult Create([DataSourceRequest]DataSourceRequest request, CategoryViewModel model)
        {
            var createdModel = base.Create<Category>(model);
            if (createdModel != null)
            {
                model.Id = createdModel.Id;
            }

            return this.GridOperation(model, request);
        }
 public void TestInitialize()
 {
     factories = Substitute.For<Factories>();
     fixture = new Fixture();
     factories.Categories.Returns(fixture.CreateMany<Category>().ToList());
     categories = factories.Categories.Select(category => new CategoryViewModel(category, factories)).ToList();
     product = new Product { CategoryId = factories.Categories.First().Id };
     product.SetOwner(factories);
     overrideCategory = new CategoryViewModel(new Category(), factories);
 }
        public ActionResult CategoryViewModels_Destroy([DataSourceRequest]DataSourceRequest request, CategoryViewModel categoryViewModel)
        {
            if (this.ModelState.IsValid)
            {
                var dbCategory = this.categoriesService.Find(categoryViewModel.Id);

                this.categoriesService.Delete(dbCategory);
            }

            return this.Json(new[] { categoryViewModel }.ToDataSourceResult(request, this.ModelState));
        }
        public ActionResult Update([DataSourceRequest]DataSourceRequest request, CategoryViewModel model)
        {
            if (model != null && this.ModelState.IsValid)
            {
                this.categories.Update(model.Id, model.Name);

                return this.GridOperationObject(model, request);
            }

            return null;
        }
示例#9
0
 /// <summary>
 /// Добавление категории в репозиторий
 /// </summary>
 /// <param name="categoryView"></param>
 public void Add(CategoryViewModel categoryView)
 {
     categoryView.CreatedDate = categoryView.UpdatedDate = DateTime.Now;
     Category category = Convert(categoryView);
     if (categoryView.ParentCategoryId == 0)
         category.ParentCategory = null;
     else
     {
         category.ParentCategory = categoryRepository.Get(categoryView.ParentCategoryId.Value);
     }
     categoryRepository.Add(category);
 }
示例#10
0
        public async Task<IHttpActionResult> Get(long id)
        {
            var entity = await _repository.GetAsync(id);
            if (entity == null)
            {
                return NotFound();
            }
            var viewModel = new CategoryViewModel();
            viewModel.Create(entity);

            return Ok(viewModel);
        }
        public ActionResult CategoryViewModels_Create([DataSourceRequest]DataSourceRequest request, CategoryViewModel categoryViewModel)
        {
            if (this.ModelState.IsValid)
            {
                var dbCategory = this.Mapper.Map<Category>(categoryViewModel);

                this.categoriesService.Add(dbCategory);
                categoryViewModel.Id = dbCategory.Id;
            }

            return this.Json(new[] { categoryViewModel }.ToDataSourceResult(request, this.ModelState));
        }
 public ActionResult Delete(CategoryViewModel model)
 {
     try
     {
         categoryService.Delete(model.CategoryId);
         return RedirectToAction("List", "Category");
     }
     catch
     {
         return View();
     }
 }
示例#13
0
        /// <summary>
        /// Удаление категории
        /// </summary>
        /// <param name="categoryView"></param>
        public void Delete(CategoryViewModel categoryView)
        {
            Category categoryForDelete = categoryRepository.Get(categoryView.Id);
            IEnumerable<Category> childCategory = categoryRepository.Get(1, categoryRepository.Count(m => true), m => m.ParentCategoryId == categoryView.Id);
            foreach (Category c in childCategory)
            {
                c.ParentCategory = categoryForDelete.ParentCategory;
                c.ParentCategoryId = categoryForDelete.ParentCategoryId;
                categoryRepository.Update(c);
            }

            categoryRepository.Delete(categoryForDelete);
        }
示例#14
0
        public ActionResult Update([DataSourceRequest]DataSourceRequest request, CategoryViewModel model)
        {
            if (model != null && this.ModelState.IsValid)
            {
                var category = this.categoriesService.GetById(model.Id);
                category.Name = model.Name;
                category.CategoryIdentifier = model.CategoryIdentifier;

                this.categoriesService.Update(category);
            }

            return this.Json(new[] { model }.ToDataSourceResult(request, this.ModelState));
        }
示例#15
0
        public async Task<IHttpActionResult> GetAll()
        {
            var all = await _repository.GetAllAsync();
            var allViewModels = new List<CategoryViewModel>();

            foreach (var entity in all)
            {
                var viewModel = new CategoryViewModel();
                viewModel.Create(entity);
                allViewModels.Add(viewModel);
            }
            return Ok(allViewModels);
        }
        public void Create(CategoryViewModel model)
        {
            Category category = new Category
            {
                CategoryName = model.CategoryName
            };

            using (var context = new WebShopMVCContext())
            {
                context.Categories.Add(category);
                context.SaveChanges();
            }
        }
示例#17
0
 public ActionResult Delete(CategoryViewModel category)
 {
     try
     {
         categoryService.Delete(category);
         categoryService.SaveChanges();
         return RedirectToAction("Index");
     }
     catch
     {
         ModelState.AddModelError("", "Unable to save changes");
     }
     return View(category);
 }
        public ActionResult CategoryViewModels_Update([DataSourceRequest]DataSourceRequest request, CategoryViewModel categoryViewModel)
        {
            if (this.ModelState.IsValid)
            {
                var dbCategory = this.categoriesService.Find(categoryViewModel.Id);
                dbCategory.Name = categoryViewModel.Name;
                dbCategory.Description = categoryViewModel.Description;

                this.categoriesService.Update(dbCategory);
                categoryViewModel = this.Mapper.Map<CategoryViewModel>(dbCategory);
            }

            return this.Json(new[] { categoryViewModel }.ToDataSourceResult(request, this.ModelState));
        }
        public ActionResult Create(CategoryViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return this.View(model);
            }

            var newCategory = this.Mapper.Map<Category>(model);
            categories.Add(newCategory);

            categories.Save();

            return RedirectToAction("Index");
        }
        public ActionResult Create([DataSourceRequest]DataSourceRequest request, CategoryViewModel model)
        {
            if (model != null && this.ModelState.IsValid)
            {
                var newCategory = this.Mapper.Map<Category>(model);

                var createdCategory = this.categories.Create(newCategory);

                model.Id = createdCategory.Id;

                return this.GridOperationObject(model, request);
            }

            return null;
        }
示例#21
0
        public ActionResult Create([DataSourceRequest] DataSourceRequest request, CategoryViewModel category)
        {
            if (ModelState.IsValid)
            {
                var categoryToCreate = new Category() 
                {
                    Id = category.Id,
                    Name = category.Name
                };

                db.Categories.Add(categoryToCreate);
                db.SaveChanges();
            }

            return Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult());
        }
        public ActionResult CategoriesDelete([DataSourceRequest]DataSourceRequest request, CategoryViewModel category)
        {
            if (ModelState.IsValid)
            {
                var toDelete = new Category()
                {
                    ID = category.Id,
                    Name = category.Name
                };

                this.Data.Categories.Attach(toDelete);
                this.Data.Categories.Remove(toDelete);
                this.Data.SaveChanges();
            }
            return Json(new[] { category }.ToDataSourceResult(request, ModelState));
        }
        public ActionResult CategoriesUpdate([DataSourceRequest]DataSourceRequest request, CategoryViewModel category)
        {
            if (ModelState.IsValid)
            {
                var newCategory = new Category()
                {
                    ID = category.Id,
                    Name = category.Name
                };
                this.Data.Categories.Attach(newCategory);
                this.Data.Entry(newCategory).State = EntityState.Modified;
                this.Data.SaveChanges();

            }
            return Json(new[] { category }.ToDataSourceResult(request, ModelState));
        }
        public ActionResult CategoriesCreate([DataSourceRequest]DataSourceRequest request, CategoryViewModel category)
        {
            if (ModelState.IsValid)
            {
                Category newCategory = new Category()
                {
                    Name = category.Name
                };

                newCategory.ID= this.Data.Categories.Add(newCategory).ID;
                this.Data.SaveChanges();
                category.Id = newCategory.ID;
            }

            return Json(new[] { category }.ToDataSourceResult(request, ModelState));
        }
        public IHttpActionResult GetCategoryById(int id)
        {
            Category category = db.Categories.FirstOrDefault(c => c.Id == id);
            if (category == null)
            {
                return NotFound();
            }

            var viewModel = new CategoryViewModel()
            {
                Id = category.Id,
                Name = category.Name
            };

            return Ok(viewModel);
        }
示例#26
0
        public ActionResult CreateCategory(CategoryViewModel model)
        {
            try
            {
                int id = model.Create();
                if (id > 0)
                {
                    return RedirectToAction("index");
                }
            }
            catch (Exception)
            {
            }

            return View(model);
        }
示例#27
0
        public ActionResult Create(CategoryViewModel categoryViewModel)
        {
            if (this.ModelState.IsValid)
            {
                var categoryDb = this.Mapper.Map<Category>(categoryViewModel);
                this.categoriesService.Add(categoryDb);

                HttpPostedFileBase photo = this.Request.Files["photo"];
                if (photo != null && photo.ContentLength > 0 && this.categoriesService is IImagesService)
                {
                    ((IImagesService)this.categoriesService).SaveImage(photo, categoryDb, this.Server.MapPath("/Img"), "/Img/");
                }

                return this.RedirectToAction("Index");
            }

            return this.View(categoryViewModel);
        }
        public ActionResult Create(CategoryViewModel model)
        {
            if (ModelState.IsValid)
            {
                var newCategory = new Category()
                {
                    Name = model.Name
                };

                this.categories.Add(newCategory);

                return Redirect("~/Home/Index");
            }
            else
            {
                return View(model);
            }
        }
        public IHttpActionResult Create(CategoryViewModel category)
        {
            if (!this.ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var newCategory = new Category
            {
                Name = category.Name
            };

            this.data.Categories.Add(newCategory);
            this.data.SaveChanges();

            category.Id = newCategory.CategoryID;
            return Ok(category);
        }
        public ActionResult CategoriesCreate([DataSourceRequest]DataSourceRequest request, CategoryViewModel category)
        {
            if (ModelState.IsValid)
            {
                var db = new LibraryDbContext();

                Category newCategory = new Category()
                {
                    Name = category.Name
                };

                newCategory.Id = db.Categories.Add(newCategory).Id;
                db.SaveChanges();
                category.Id = newCategory.Id;
            }
            
            return Json(new[] { category }.ToDataSourceResult(request, ModelState));
        }
示例#31
0
        public ActionResult Edit(string id)
        {
            ObjectId objectId = new ObjectId(id);

            var category = this.mongoContext.Categories.Find(c => c.Id.Equals(objectId)).First();

            if (category.Name.Equals("CATEGORY"))
            {
                TempData["Error"] = "You can't edit this category.";
                return(RedirectToAction(nameof(Index)));
            }

            var categories = this.mongoContext.Categories.AsQueryable().ToEnumerable();

            TempData["Categories"] = categories;

            CategoryViewModel categoryViewModel = new CategoryViewModel
            {
                Name   = category.Name,
                Father = category.Father.ToString()
            };

            return(View(categoryViewModel));
        }
示例#32
0
 public IActionResult Update(CategoryViewModel category)
 {
     try{
         if (ModelState.IsValid)
         {
             var model = new CategoryModel()
             {
                 Id          = category.Id,
                 Name        = category.Name,
                 Alias       = category.Alias,
                 IsMenu      = category.IsMenu,
                 Activated   = category.Activated,
                 Orders      = category.Orders,
                 Description = category.Description
             };
             _repo.Update(model);
             return(RedirectToAction("Index"));
         }
         return(View());
     }catch (Exception ex) {
         ModelState.AddModelError("", ex.Message);
         return(View());
     }
 }
示例#33
0
        /// <summary>
        /// カテゴリリストを更新する
        /// </summary>
        /// <param name="categoryId">選択対象のカテゴリID</param>
        /// <returns></returns>
        private async Task UpdateCategoryListAsync(int?categoryId = null)
        {
            ObservableCollection <CategoryViewModel> categoryVMList = new ObservableCollection <CategoryViewModel>()
            {
                new CategoryViewModel()
                {
                    Id = -1, Name = "(指定なし)"
                }
            };
            int?tmpCategoryId = categoryId ?? this.WVM.SelectedCategoryVM?.Id ?? categoryVMList[0].Id;
            CategoryViewModel selectedCategoryVM = categoryVMList[0];

            using (DaoBase dao = this.builder.Build()) {
                DaoReader reader = await dao.ExecQueryAsync(@"
SELECT category_id, category_name FROM mst_category C 
WHERE del_flg = 0 AND EXISTS (SELECT * FROM mst_item I WHERE I.category_id = C.category_id AND balance_kind = @{0} AND del_flg = 0 
  AND EXISTS (SELECT * FROM rel_book_item RBI WHERE book_id = @{1} AND RBI.item_id = I.item_id)) 
ORDER BY sort_order;", (int)this.WVM.SelectedBalanceKind, this.WVM.SelectedBookVM.Id);

                reader.ExecWholeRow((count, record) => {
                    CategoryViewModel vm = new CategoryViewModel()
                    {
                        Id = record.ToInt("category_id"), Name = record["category_name"]
                    };
                    categoryVMList.Add(vm);
                    if (vm.Id == tmpCategoryId)
                    {
                        selectedCategoryVM = vm;
                    }
                    return(true);
                });
            }

            this.WVM.CategoryVMList     = categoryVMList;
            this.WVM.SelectedCategoryVM = selectedCategoryVM;
        }
        public async Task <IActionResult> CreateCategory(CategoryViewModel categoryView)
        {
            //TODO validation
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var categoryDto = new CategoryDTO {
                Name = categoryView.Name
            };
            var operationDetails = await _action.Create(categoryDto);

            if (operationDetails.Succeeded)
            {
                categoryView.Id = _categoryService.GetCategoryIdByName(categoryDto.Name);
                return(CreatedAtAction("GetCategory", new { id = categoryView.Id }, categoryView));
            }
            else
            {
                ModelState.AddModelError(operationDetails.Property, operationDetails.Message);
                return(BadRequest(ModelState));
            }
        }
示例#35
0
 public ActionResult Add()
 {
     try
     {
         var vendor = (OctopusCodesMultiVendor.Models.Vendor)SessionPersister.account;
         CategoryViewModel categoryViewModel = new CategoryViewModel()
         {
             category = new Category()
             {
                 Status = true
             },
             Parent = ocmde.Categories.Where(c => c.ParentId == null).Select(c => new SelectListItem()
             {
                 Value = c.Id.ToString(),
                 Text  = c.Name
             }).ToList()
         };
         return(View("Add", categoryViewModel));
     }
     catch (Exception e)
     {
         return(View("Error", new HandleErrorInfo(e, "Category", "Add")));
     }
 }
示例#36
0
        public ActionResult Edit(CategoryViewModel model, int id)
        {
            var temp = _categoryRepository.GetByID(id);

            if (!ModelState.IsValid)
            {
                CategoryViewModel model1 = new CategoryViewModel()
                {
                    CategoryId   = temp.CategoryId,
                    CategoryName = temp.CategoryName,
                    Image_url    = temp.Image_url
                };

                return(View(model1));
            }

            var item = _categoryRepository.GetByID(id);

            item.CategoryName = model.CategoryName;
            item.Image_url    = model.Image_url;
            _categoryRepository.Update(item);

            return(RedirectToAction("Index"));
        }
示例#37
0
        public async Task <ActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Category category = await context.Categories.FindAsync(id);

            if (category == null)
            {
                return(HttpNotFound());
            }

            CategoryViewModel categoryViewModel = new CategoryViewModel()
            {
                Id = category.Id,
                ParentCategoryId = category.ParentCategoryId,
                CategoryName     = category.CategoryName
            };


            ViewBag.ParentCategoryIdSelectList = PopulateParentCategorySelectList(categoryViewModel.Id);
            return(View(categoryViewModel));
        }
        public ActionResult AddProduct(CategoryViewModel cvm, HttpPostedFileBase file)
        {
            var Categories = db.categories.ToList();

            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    cvm.Product.Image = file.FileName;
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            }
            else
            {
                if (!ModelState.IsValid)
                {
                    cvm.Categories = Categories;
                    return(View("AddProduct", cvm));
                }
            }

            db.products.Add(cvm.Product);


            var v = db.categories.Single(c => c.Id == cvm.Product.CategoryID);

            v.Number_of_products++;

            db.SaveChanges();
            return(RedirectToAction("AddProduct"));
        }
示例#39
0
        public ActionResult Index(CategoryViewModel collection)
        {
            var request = new FilteredModel <Category>
            {
                PageIndex = collection.ThisPageIndex,
                Order     = collection.PageOrder,
                OrderBy   = collection.PageOrderBy
            };
            var offset = (request.PageIndex - 1) * request.PageSize;
            var result = _mapper.Map <IList <CategoryViewModel> >(_categoryService.GetPaging(_mapper.Map <Category>(collection), out long totalCount, request.OrderBy, request.Order, offset, request.PageSize));

            if (!result.Any() && totalCount > 0 && request.PageIndex > 1)
            {
                request.PageIndex = (int)(totalCount / request.PageSize);
                if (totalCount % request.PageSize > 0)
                {
                    request.PageIndex++;
                }
                result = _mapper.Map <IList <CategoryViewModel> >(_categoryService.GetPaging(_mapper.Map <Category>(collection), out totalCount, request.OrderBy, request.Order, offset, request.PageSize));
            }
            ViewBag.OnePageOfEntries = new StaticPagedList <CategoryViewModel>(result, request.PageIndex, request.PageSize, (int)totalCount);
            ViewBag.SearchModel      = collection;
            return(View());
        }
示例#40
0
        public ActionResult CreateAdvertisement()
        {
            CreateAdverstisementViewModel viewModel = new CreateAdverstisementViewModel();

            viewModel.Locations    = new List <Location>();
            viewModel.Locations    = db.Locations.ToList();
            viewModel.Difficulties = new List <Difficulty>();
            viewModel.Difficulties = db.Difficulties.ToList();

            viewModel.AvaibleCategories = new List <CategoryViewModel>();
            var categories = db.Categories;

            foreach (Category c in categories)
            {
                var cvm = new CategoryViewModel();
                cvm.Id   = c.Id;
                cvm.Name = c.Name;
                viewModel.AvaibleCategories.Add(cvm);
            }

            viewModel.SelectedCategories = new List <CategoryViewModel>();

            return(View(viewModel));
        }
示例#41
0
        public ActionResult AddCategory(CategoryViewModel model)
        {
            SqlConnection connection = new SqlConnection(Constr);

            connection.Open();

            if (ModelState.IsValid)
            {
                string cmd2 = string.Format("INSERT INTO Category(Name) VALUES('{0}')", model.Name);

                SqlCommand cmd = new SqlCommand(cmd2, connection);
                cmd.ExecuteNonQuery();
                connection.Close();
                ModelState.Clear();
                TempData["Message"] = "New Category Added";
                return(RedirectToAction("AllCategories", "Admin"));
            }
            else
            {
                ModelState.Clear();

                return(View(model));
            }
        }
示例#42
0
 //        [Route("Admin/Categories/Edit")]
 public IActionResult Edit(int id, CategoryViewModel categoryView)
 {
     if (ModelState.IsValid)
     {
         try
         {
             _context.Update(categoryView.Category);
             _context.SaveChanges();
         }
         catch (DbUpdateConcurrencyException)
         {
             if (!CategoryExists(categoryView.Category.Id))
             {
                 return(NotFound());
             }
             else
             {
                 throw;
             }
         }
         return(RedirectToAction(nameof(Index)));
     }
     return(View());
 }
示例#43
0
        public ActionResult Category(int?categoryId)
        {
            var categories = db.Categories.Include(c => c.foodList);
            CategoryViewModel viewModel = new CategoryViewModel();

            viewModel.foodList = new List <FoodItem>();
            if (categoryId != null)
            {
                ViewBag.CategoryID = categoryId;

                var foodList = categories
                               .Where(c => c.ID == categoryId)
                               .Single()
                               .foodList;

                viewModel.foodList = FilterFoodItems(foodList);
            }

            viewModel.Category = categories.ToList();

            ViewBag.ReturnUrl = Url.Action("Category", "Home");

            return(View(viewModel));
        }
示例#44
0
        public CategoryViewModel GetCategoryByName(string categoryName)
        {
            var category = this.Data.Categories
                           .All()
                           .Where(c => c.Name == categoryName)
                           .Select(c => new
            {
                BookCovers = c.Books
                             .OrderBy(b => b.Title)
                             .Select(b => b.CoverImageUrl),
                BookTitles = c.Books
                             .OrderBy(b => b.Title)
                             .Select(b => b.Title)
            })
                           .First();

            var categoryViewModel = new CategoryViewModel
            {
                BookCovers = category.BookCovers,
                BookTitles = category.BookTitles
            };

            return(categoryViewModel);
        }
示例#45
0
        public ActionResult CreateCategory(Int32 id)
        {
            if (Request.Cookies["MagazineId"].Value == null)
            {
                SetMessage("Lo sentimos, ha ocurrido un error. Inténtelo de nuevo.", BootstrapAlertTypes.Danger); return(RedirectToAction("Index", "Magazines"));
            }
            int magId = Int32.Parse(Request.Cookies["MagazineId"].Value);

            var user     = UserService.GetCurrentUser();
            var relation = UserService.UserInMagazine(id, user.UserId);

            if (!relation || !ModelState.IsValid)
            {
                return(RedirectToAction("Index", "Magazines"));
            }

            var model = new CategoryViewModel
            {
                MagazineId        = id,
                ParentsCategories = MagazineService.GetCategoriesByMagazineId(magId)
            };

            return(View(model));
        }
示例#46
0
        public async Task <IActionResult> Edit(Guid?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var getOperation = await _bo.ReadAsync((Guid)id);

            if (!getOperation.Success)
            {
                return(View("Error", new ErrorViewModel()
                {
                    RequestId = getOperation.Exception.Message
                }));
            }
            if (getOperation.Result == null)
            {
                return(NotFound());
            }
            var vm = CategoryViewModel.Parse(getOperation.Result);

            return(View(vm));
        }
示例#47
0
        public async Task <IActionResult> Update([FromBody] CategoryViewModel categoryViewModel, int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userId = _userManager.GetUserId(User);

            if (userId == null)
            {
                return(StatusCode(401));
            }

            if (await _repository.GetByIdAsync(id, userId) == null)
            {
                return(NotFound());
            }

            Category category = new Category()
            {
                Id     = id,
                Name   = categoryViewModel.Name,
                LogoId = categoryViewModel.LogoId,
                UserId = userId
            };

            if (await _repository.UpdateAsync(category))
            {
                return(Ok());
            }
            else
            {
                return(StatusCode(500));
            }
        }
示例#48
0
        public IActionResult Delete(long id)
        {
            Category _category = _categoryRepository.GetSingle(u => u.Id == id);

            if (_category != null)
            {
                _categoryRepository.Delete(_category);
                _categoryRepository.Commit();
                CategoryViewModel _categoryVM = _mapper.Map <Category, CategoryViewModel>(_category);
                Log.Information("Category {@_categoryVM} Deleted from database", _categoryVM);
                return(new OkObjectResult(new ResultVM()
                {
                    Status = Status.Success, Message = "Succesfully Deleted Category: " + _categoryVM.title, Data = _categoryVM
                }));
            }
            else
            {
                Log.Error("Error Occured Deleting Category from database");
                return(NotFound(new ResultVM()
                {
                    Status = Status.Error, Message = "An Error Occured: ", Data = null
                }));
            }
        }
示例#49
0
        internal static void SetCategoryToCategoryViewModel(CategoryViewModel viewModel, Category model)
        {
            viewModel.Name          = model.Name;
            viewModel.Subcategories = new ObservableCollection <SubcategoryViewModel>();

            foreach (Subcategory subcategory in model.Subcategories)
            {
                SubcategoryViewModel subcategoryViewModel = new SubcategoryViewModel
                {
                    SubName = subcategory.Name,
                    Faqs    = new ObservableCollection <FaqViewModel>(),
                };
                foreach (Faq faq in subcategory.Faqs)
                {
                    FaqViewModel faqViewModel = new FaqViewModel
                    {
                        AnswerText = faq.AnswerText,
                        Question   = faq.Question
                    };
                    subcategoryViewModel.Faqs.Add(faqViewModel);
                }
                viewModel.Subcategories.Add(subcategoryViewModel);
            }
        }
 public IActionResult Create(CategoryViewModel model)
 {
     if (model == null)
     {
         return(NotFound());
     }
     if (ModelState.IsValid)
     {
         var category = _mapper.Map <CategoryViewModel, Category>(model);
         category.AddedBy   = _admin.Name;
         category.AddedDate = DateTime.Now;
         if (model.Images != null)
         {
             category.Image = _fileManager.Upload(model.Images);
         }
         else
         {
             category.Image = null;
         }
         _categoryRepository.AddCategory(category);
         return(RedirectToAction("index"));
     }
     return(View(model));
 }
示例#51
0
        public void OnGet(int? id)
        {
            try
            {
                if (!id.HasValue)
                {
                    TempData["MessageError"] = "Categoria não encontrada";
                    RedirectToPage("Index");
                }

                Category = _categoryService.GetById(id.Value);

                if (Category == null)
                {
                    TempData["MessageError"] = "Categoria não encontrada";
                    RedirectToPage("Index");
                }
            }
            catch (Exception ex)
            {
                TempData["MessageError"] = ex.Message;
                RedirectToPage("Index");
            }
        }
示例#52
0
        public CategoryViewModel ProduceCategoryEditModel(Category category)
        {
            var dropDownItems = this.categoryService.GetAll()
                                .Where(x => x.Id != category.Id)
                                .Select(x => new MultiSelectDropDownListItem
            {
                Id      = x.Id.ToString(),
                Text    = x.Name,
                Checked = false,
            })
                                .ToList();

            var subcategoriesIds = category.Subcategories.Select(x => x.Id.ToString());

            foreach (var listItem in dropDownItems)
            {
                if (subcategoriesIds.Contains(listItem.Id))
                {
                    listItem.Checked = true;
                }
            }

            var vm = new CategoryViewModel
            {
                Id        = category.Id,
                Name      = category.Name,
                Order     = category.DisplayOrder,
                Visible   = category.Visible,
                IsPrimary = category.IsPrimary,
            };

            vm.Subcategories.ListItems   = dropDownItems;
            vm.PictureSelector.PictureId = category.PictureId;

            return(vm);
        }
 public override ActionResult EditCategory(CategoryViewModel viewModel)
 {
     if (ModelState.IsValid)
     {
         var type   = db.Category_types.Find(viewModel.TypeId);
         var parent = db.Categories.Find(viewModel.ParentId);
         if (type != null && parent != null)
         {
             var category = db.Categories.Find(viewModel.CategoryId);
             if (category != null)
             {
                 category.Name            = viewModel.Name;
                 category.Description     = viewModel.Desciption;
                 db.Entry(category).State = System.Data.Entity.EntityState.Modified;
                 var result = db.SaveChanges();
                 if (result > 0)
                 {
                     return(RedirectToAction("Index", new { id = type.Id }));
                 }
             }
         }
     }
     return(View(viewModel));
 }
示例#54
0
        public ActionResult Add(CategoryViewModel categoryViewModel)
        {
            string message = "";
            if (ModelState.IsValid)
            {

                Category category = Mapper.Map<Category>(categoryViewModel);

                if (_categoryManager.Add(category))
                {
                    message = "save";

                }
                else
                {
                    message = "not saved";
                }

            }

            categoryViewModel.Categories = _categoryManager.GetAll();
            ViewBag.Message = message;
            return View(categoryViewModel);
        }
示例#55
0
        public async Task <ServiceResult <int> > Get(ClaimsPrincipal user, int groupId, int categoryId)
        {
            var group = groupsRepository.Get(groupId);

            if (group is null)
            {
                return(ServiceResult <int> .Error(404, "Group was not found"));
            }

            var authorizationResult = await authorizationService.AuthorizeAsync(user, group, GroupOperations.Read);

            if (!authorizationResult.Succeeded)
            {
                return(ServiceResult <int> .Error(401, "Unauthorized"));
            }

            var category = categoriesRepository.Get(categoryId);

            if (category is null || category.GroupId != groupId)
            {
                return(ServiceResult <int> .Error(404, "Category was not found"));
            }
            return(ServiceResult <int> .Success(CategoryViewModel.FromModel(category)));
        }
示例#56
0
        public async Task <IActionResult> EditCategory(CategoryViewModel model)
        {
            if (ModelState.IsValid)
            {
                var ecc = new EditCategoryCommand()
                {
                    Id             = model.Id,
                    NewName        = model.Name,
                    NewDescription = model.Description
                };

                var result = await _cp.ProcessAsync(ecc);

                if (result.Succeeded)
                {
                    return(RedirectToAction("ManageCategories"));
                }
                else
                {
                    return(NotFound());
                }
            }
            return(View(model));
        }
        public async Task <IActionResult> Edit(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var category = await _categoryServices.GetByIdAsync(id);

            if (category == null)
            {
                return(NotFound());
            }

            var categoryViewModel = new CategoryViewModel()
            {
                Id      = category.Id,
                Slug    = category.Slug,
                Name    = category.Name,
                Content = category.Content,
            };

            return(View(categoryViewModel));
        }
示例#58
0
        public ActionResult AddCategory(CategoryViewModel model)
        {
            if (ModelState.IsValid)
            {
                model.Category.CategoryCreatedUserId  = ((User)Session["CurrentUser"]).Id;
                model.Category.CategoryCreatedDate    = DateTime.Now;
                model.Category.CategoriModifiedDate   = DateTime.Now;
                model.Category.CategoryModifiedUserId = ((User)Session["CurrentUser"]).Id;
                model.Category.User = ((User)Session["CurrentUser"]);
                new CategoryManager().Add(model.Category);
            }

            else
            {
                ErrorViewModal errorViewModel = new ErrorViewModal()
                {
                    Title          = "Model Yanlış!",
                    RedirectingUrl = "/Category/AddCategory"
                };

                return(View("Error", errorViewModel));
            }
            return(RedirectToAction("ListCategory", "Category"));
        }
示例#59
0
        public async Task EditCategoryAsync(int id, CategoryViewModel model)
        {
            try
            {
                var category = this.categoryRepository.All().FirstOrDefault(e => e.Id == id);

                if (category == null)
                {
                    throw new ApplicationException(string.Format(ErrorMessages.CategoryDoesNotExist, id));
                }

                category.Name = model.Name;

                this.categoryRepository.Update(category);

                await this.categoryRepository.SaveChangesAsync();

                this.logger.LogInformation(string.Format(LogMessages.CategoryAdded, category.Id));
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }
示例#60
0
        public async Task <GenericResult> Save(CategoryViewModel <T> categoryViewModel)
        {
            var category = categoryViewModel.ConvertToCategory();

            return(await Save(category));
        }