public async Task <IActionResult> Create(CreateCategoryViewModel model) { if (ModelState.IsValid) { var identityUser = await _userManager.GetUserAsync(HttpContext.User); string path = "/img/no_image.jpg"; if (model.TitleImage != null) { FileSaverResult fileSaverResult = await _fileSaver.SaveCategoryTitleImage(_appEnvironment.WebRootPath, model.TitleImage); if (fileSaverResult.IsSuccessful) { path = fileSaverResult.Path; } else { ModelState.AddModelError("", "Can't save image"); } } var result = await Mediator.Send(new CreateCategoryCommand { Title = model.Title, IdentityUserId = identityUser.Id, TitleImagePath = path, }); if (result.IsSuccessful) { if (model.TitleImage != null) { using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)) { await model.TitleImage.CopyToAsync(fileStream); } } return(RedirectToAction("Index", "Category")); } else { ModelState.AddModelError("", result.Message); } } return(View()); }
public async Task <ActionResult> Create(CreateCategoryViewModel model) { if (ModelState.IsValid) { ApplicationCategory category = new ApplicationCategory { CategoryName = model.CategoryName, UserId = User.Identity.GetUserId() }; db.Categories.Add(category); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(model)); }
public ActionResult CreateCategory(CreateCategoryViewModel model) { if (!ModelState.IsValid) { return(View()); } var category = new Category { Name = model.Name }; context.Categories.Add(category); context.SaveChanges(); return(RedirectToAction(nameof(Index))); }
public async Task CallCategoryServiceOnce() { var categoryName = "Ivan"; var categoryServiceMocked = new Mock <ICategoryService>(); var mapperMocked = new Mock <IMappingProvider>(); var createCategoryViewModel = new CreateCategoryViewModel { CategoryName = categoryName }; var categoryController = new CategoryController(categoryServiceMocked.Object, mapperMocked.Object); await categoryController.CreateCategory(createCategoryViewModel); categoryServiceMocked.Verify(c => c.AddCategory(categoryName), Times.Once); }
public ActionResult Create(CreateCategoryViewModel model) { if (ModelState.IsValid) { List <Domain.Entities.Utilities.Attribute> catAttrs = new List <Domain.Entities.Utilities.Attribute>(); var nameStr = Request.Form["AtrbName"]; if (nameStr is null) { nameStr = ""; } var atrbNames = nameStr.Split(',').Select(sValue => sValue.Trim()).ToList() as List <string>; if (atrbNames is null) { atrbNames = new List <string>(); } foreach (var atrbName in atrbNames) { if (atrbName != "") { catAttrs.Add(new Domain.Entities.Utilities.Attribute() { Name = atrbName }); } } foreach (var atrb in catAttrs) { if (model.Attributes == null) { model.Attributes = new List <Domain.Entities.Utilities.Attribute>(); } model.Attributes.Add(atrb); } db.Categories.Add(new Category { Name = model.Name, IsBase = model.IsBase, DisplayOrder = 0, Description = model.Description, Attributes = model.Attributes, CategoryId = model.Id }); db.SaveChanges(); return(RedirectToAction("Index", "Category")); } return(View(model)); }
public async Task <ActionResult> Create([Bind(Include = "Name,ParentCategoryId")] CreateCategoryViewModel createCategoryViewModel) { if (ModelState.IsValid) { Category category = new Category() { Name = createCategoryViewModel.Name, ParentCategory = await db.Categories.FindAsync(createCategoryViewModel.ParentCategoryId) }; db.Categories.Add(category); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(createCategoryViewModel)); }
public async Task <Category> CreateCategory(CreateCategoryViewModel createcategoryViewModel, ClaimsPrincipal claimsPrincipal) { Category category = createcategoryViewModel.Category; category = await postService.AddCategory(category); string webRootPath = webHostEnvironment.WebRootPath; string pathToImage = $@"{webRootPath}\UserFiles\Categories\{category.ID}\HeaderImage.jpg"; EnsureFolder(pathToImage); using (var fileStream = new FileStream(pathToImage, FileMode.Create)) { await createcategoryViewModel.BlogHeaderImage.CopyToAsync(fileStream); } logger.LogInformation("PostBusinessManager: CreateCategory OK."); return(category); }
public ActionResult Create(int?Id) { // Household Id if (Id is null) { TempData.Add("Message", "Improper Id"); TempData.Add("MessageColour", "danger"); return(RedirectToAction("Index", "Household")); } var viewModel = new CreateCategoryViewModel() { HouseholdId = (int)Id }; return(View(viewModel)); }
public IActionResult Create(CreateCategoryViewModel vm) { var user = GetCurrentUserAsync().Result; Category category = new Category() { Name = vm.Name, Description = vm.Description, PhotoPath = vm.PhotoPath, UserId = user.Id, Active = true }; _categoryRepo.Create(category); return(RedirectToAction("Index", "Admin")); }
public async Task ReturnCorrectViewModel() { var categoryName = "Ivan"; var categoryServiceMocked = new Mock <ICategoryService>(); var mapperMocked = new Mock <IMappingProvider>(); var createCategoryViewModel = new CreateCategoryViewModel { CategoryName = categoryName }; var categoryController = new CategoryController(categoryServiceMocked.Object, mapperMocked.Object); var result = await categoryController.CreateCategory(createCategoryViewModel); Assert.IsInstanceOfType(result, typeof(JsonResult)); }
public async Task <IActionResult> Create(int id) { var organization = await _bll.OrganizationsService.GetOrganizationMinAsync(organizationId : id); if (organization == null) { return(BadRequest()); } var vm = new CreateCategoryViewModel { OrganizationName = organization.Name, OrganizationId = organization.Id }; return(View(vm)); }
public async Task <IActionResult> Create(CreateCategoryViewModel model) { if (ModelState.IsValid) { var category = new Category { Name = model.Name, Description = model.Description }; _context.Categories.Add(category); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(model)); }
public IActionResult Create(CreateCategoryViewModel model) { if (ModelState.IsValid) { //TODO: set message var category = model.ToEntity(); var categories = new List <Category> { category }; _unitOfWork.BookMetas.AddCategories(categories); _unitOfWork.SaveChanges(); return(RedirectToAction("Index")); } //TODO: set message return(View(model)); }
public ActionResult Create(CreateCategoryViewModel createCategoryViewModel) { if (ModelState.IsValid) { var category = new Category() { Name = createCategoryViewModel.Name, ContextId = GetCurrentContextId() }; _categoryService.Add(category); return(RedirectToAction("Index")); } else { SendModelStateErrors(); return(View(createCategoryViewModel)); } }
public async Task <IActionResult> CreateCategory(CreateCategoryViewModel model) { if (ModelState.IsValid) { Category category = new Category { Name = model.Name }; await _context.Categories.AddAsync(category); await _context.SaveChangesAsync(); return(RedirectToAction("Categories")); } return(View(model)); }
public ActionResult CreateCategory(int id, CreateCategoryViewModel formData) { if (!ModelState.IsValid) { ViewBag.HouseHoldId = id; return(View(formData)); } var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {ViewBag.Token}"); var parameters = new List <KeyValuePair <string, string> >(); parameters.Add(new KeyValuePair <string, string>("HouseHoldId", id.ToString())); parameters.Add(new KeyValuePair <string, string>("Name", formData.Name)); parameters.Add(new KeyValuePair <string, string>("Description", formData.Description)); var enCodeParameters = new FormUrlEncodedContent(parameters); var url = $"http://localhost:55336/api/Category/Create/"; var response = httpClient.PostAsync(url, enCodeParameters).Result; if (response.StatusCode == System.Net.HttpStatusCode.OK) { TempData["Message"] = "Category was created successfully"; return(RedirectToAction("ListOfHouseHoldForCategory", "Category")); } else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { var data = response.Content.ReadAsStringAsync().Result; var result = JsonConvert.DeserializeObject <APIErrorData>(data); foreach (var ele in result.ModelState) { ModelState.AddModelError("", ele.Value[0].ToString()); } return(View(formData)); } else { return(RedirectToAction("Error", "Home")); } }
public async Task <IActionResult> CreateCategory(CreateCategoryViewModel model) { if (!this.ModelState.IsValid) { return(BadRequest("Invalid parameters!")); } try { await this.categoryService.AddCategory(model.CategoryName); return(Json(model)); } catch (ArgumentException ex) { this.ModelState.AddModelError("Error", ex.Message); return(BadRequest(ex.Message)); } }
public ActionResult CreateCategory(CreateCategoryViewModel model) { if (!ModelState.IsValid) { return(View(model)); } using (var db = new WebStoreModel()) { var category = new ProductCategory { Name = model.Name }; db.ProductCategories.Add(category); db.SaveChanges(); } return(RedirectToAction("Index")); }
public ActionResult CreateCategory(CreateCategoryViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } Category catName = new Category { CategoryName = viewModel.CategoryName, FilterButtonName = viewModel.FilterButtonName }; ApplicationDbContext.Categories.Add(catName); ApplicationDbContext.SaveChanges(); ModelState.Clear(); return(View()); }
public ActionResult Create(CreateCategoryViewModel model) { if (!ModelState.IsValid) { return(View(model)); } using (var db = new EShopContext()) { var category = new Category { CategoryName = model.CategoryName, CategoryDescription = model.Description }; db.CategoriesTable.Add(category); db.SaveChanges(); } return(RedirectToAction("Index")); }
public ActionResult Create() { List <Category> list = _context.dbCategories.ToList(); List <SelectListItem> selected = new List <SelectListItem>(); foreach (var item in list) { selected.Add(new SelectListItem() { Value = item.Id.ToString(), Text = item.Name }); } CreateCategoryViewModel cat = new CreateCategoryViewModel(); cat.Categories = selected; return(View(cat)); }
public ActionResult CreateCategory(CreateCategoryViewModel categoryViewModel) { if (ModelState.IsValid) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { try { var category = new Category { Name = categoryViewModel.Name, Description = categoryViewModel.Description, IsLocked = categoryViewModel.IsLocked, SortOrder = categoryViewModel.SortOrder, }; if (categoryViewModel.ParentCategory != null) { category.ParentCategory = _categoryService.Get(categoryViewModel.ParentCategory.Value); } _categoryService.Add(category); // We use temp data because we are doing a redirect TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel { Message = "Category Created", MessageType = GenericMessages.success }; unitOfWork.Commit(); } catch (Exception) { unitOfWork.Rollback(); } } } return(RedirectToAction("Index")); }
public ActionResult InsertImage(string name, string description, bool IsDeleted, HttpPostedFileBase file) { var viewModel = new CreateCategoryViewModel(); // get the user role viewModel.CreatedBy = User.Identity.GetUserId(); // need to initialise the date. it will get reset when the category is saved to the database with upto date datetime value viewModel.CreateDate = DateTime.UtcNow; viewModel.Name = name; viewModel.Description = description; viewModel.IsDeleted = IsDeleted; if (file != null && file.ContentLength > 0) { try { if (System.IO.File.Exists(Path.Combine(Server.MapPath("~/Content/Images"), Path.GetFileName(file.FileName)))) { ViewBag.Message = "The file already exists on the sever. Please choose another file"; return(View("Create", viewModel)); } // clear the temp folder of any old files left here clearFolder(Server.MapPath("~/Content/Images/Temp")); file.SaveAs(Path.Combine(Server.MapPath("~/Content/Images/Temp"), Path.GetFileName(file.FileName))); viewModel.ImageIsInserted = true; viewModel.ImagePath = file.FileName; ViewBag.Message = "File uploaded successfully. You must save the record to complete this action"; } catch (Exception ex) { ViewBag.Message = "ERROR:" + ex.Message.ToString(); } } else { ViewBag.Message = "You have not specified a file."; } return(View("Create", viewModel)); }
public async Task CreateCategoryTest() { var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options; var dbContext = new ApplicationDbContext(options); var repository = new EfDeletableEntityRepository <Category>(dbContext); var service = new CategoriesService(repository); var category = new CreateCategoryViewModel { Description = "Test", ImageUrl = "Test", Name = "Test", }; await service.CreateCategoryAsync(category); Assert.True(service.CategoryExist("Test")); }
public IActionResult Create(CreateCategoryViewModel model) { if (!ModelState.IsValid) { model.Accounts = AccountsSelectListItems(); return(View(model)); } var category = new Category( accountID: model.AccountID.Value, name: model.Name ); Db.InsertOrUpdate(category); UnitOfWork.CommitChanges(); return(RedirectToAction(nameof(Index))); }
// GET: Category public async Task <ActionResult> Index() { try { List <CreateCategoryViewModel> createCategoryViewModels = new List <CreateCategoryViewModel>(); List <Category> categories = await _categoryRepository.GetAllAsync(); foreach (var cat in categories) { CreateCategoryViewModel cvm = new CreateCategoryViewModel(cat); createCategoryViewModels.Add(cvm); } return(View("Index", createCategoryViewModels)); } catch { ViewBag.Message = "Something went wrong"; return(View("Error")); } }
public async Task ThrowArgumentException_WhenCategoryExists() { var categoryName = "Ivan"; var categoryServiceMocked = new Mock <ICategoryService>(); var mapperMocked = new Mock <IMappingProvider>(); var createCategoryViewModel = new CreateCategoryViewModel { CategoryName = categoryName }; categoryServiceMocked.Setup(c => c.AddCategory(categoryName)) .ThrowsAsync(new ArgumentException()); var categoryController = new CategoryController(categoryServiceMocked.Object, mapperMocked.Object); var result = await categoryController.CreateCategory(createCategoryViewModel); Assert.AreEqual(result.GetType(), typeof(BadRequestObjectResult)); }
public IActionResult CreateCategory(CreateCategoryViewModel createCategoryViewModel) { if (!ModelState.IsValid) { return(View(createCategoryViewModel)); } var category = new Category(Guid.NewGuid(), createCategoryViewModel.CategoryName); var categories = _categoryRepository.GetAll(); if (categories.Any(e => e.Name.ToLower().Equals(category.Name.ToLower()))) { ModelState.AddModelError(string.Empty, $"Category '{category.Name}' already exists"); return(View(createCategoryViewModel)); } _categoryRepository.AddOne(category); return(RedirectToAction(IndexAction, DefaultController)); }
public IActionResult CreateCategory(CreateCategoryViewModel model) { if (ModelState.IsValid) { Category newCategory = new Category { Name = model.Name }; categoryService.Add(newCategory); return(RedirectToAction("index")); } var GetAllCategories = categoryService.GetAllCategory(); CreateCategoryViewModel createCategoryViewModel = new CreateCategoryViewModel() { Categories = GetAllCategories }; return(View(createCategoryViewModel)); }
// GET: /Categories/Create public async Task <ActionResult> Create(int?parentId) { if (parentId == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Category category = await db.Categories.FindAsync(parentId); if (category == null) { return(HttpNotFound()); } var createCategoryViewModel = new CreateCategoryViewModel() { ParentCategoryId = category.Id }; return(View(createCategoryViewModel)); }