source: StockMaster/Controllers/CategoryController.cs@ dfe03b8

main
Last change on this file since dfe03b8 was dfe03b8, checked in by Ceyda <ceyda.huseini@…>, 3 days ago

Initialize StockMaster project

  • Property mode set to 100644
File size: 2.9 KB
Line 
1using Microsoft.AspNetCore.Mvc;
2using StockMaster.Data;
3using StockMaster.Models;
4using Microsoft.EntityFrameworkCore;
5using System.Threading.Tasks;
6
7namespace StockMaster.Controllers
8{
9 public class CategoryController : BaseController
10 {
11 private readonly StockDbContext _context;
12
13 public CategoryController(StockDbContext context)
14 {
15 _context = context;
16 }
17
18 public async Task<IActionResult> Index()
19 {
20 var categories = await _context.Categories
21 .OrderBy(c => c.Name)
22 .ToListAsync();
23 return View(categories);
24 }
25
26 [HttpGet]
27 public IActionResult Create()
28 {
29 return View();
30 }
31
32 [HttpPost]
33 public async Task<IActionResult> Create(Category category)
34 {
35 if (ModelState.IsValid)
36 {
37 try
38 {
39 _context.Categories.Add(category);
40 await _context.SaveChangesAsync();
41 TempData["Success"] = "Category created successfully";
42 return RedirectToAction("Index");
43 }
44 catch
45 {
46 ModelState.AddModelError("", "Failed to create category");
47 }
48 }
49 return View(category);
50 }
51
52 [HttpGet]
53 public async Task<IActionResult> Edit(int id)
54 {
55 var category = await _context.Categories.FindAsync(id);
56 if (category == null)
57 return NotFound();
58
59 return View(category);
60 }
61
62 [HttpPost]
63 public async Task<IActionResult> Edit(Category category)
64 {
65 if (ModelState.IsValid)
66 {
67 try
68 {
69 _context.Categories.Update(category);
70 await _context.SaveChangesAsync();
71 TempData["Success"] = "Category updated successfully";
72 return RedirectToAction("Index");
73 }
74 catch
75 {
76 ModelState.AddModelError("", "Failed to update category");
77 }
78 }
79 return View(category);
80 }
81
82 [HttpPost]
83 public async Task<IActionResult> Delete(int id)
84 {
85 try
86 {
87 var category = await _context.Categories.FindAsync(id);
88 if (category != null)
89 {
90 _context.Categories.Remove(category);
91 await _context.SaveChangesAsync();
92 TempData["Success"] = "Category deleted successfully";
93 }
94 }
95 catch
96 {
97 TempData["Error"] = "Cannot delete category. It may be in use.";
98 }
99 return RedirectToAction("Index");
100 }
101 }
102}
Note: See TracBrowser for help on using the repository browser.