source: StockMaster/Controllers/CustomerController.cs

main
Last change on this file 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 CustomerController : BaseController
10 {
11 private readonly StockDbContext _context;
12
13 public CustomerController(StockDbContext context)
14 {
15 _context = context;
16 }
17
18 public async Task<IActionResult> Index()
19 {
20 var customers = await _context.Customers
21 .OrderBy(c => c.Name)
22 .ToListAsync();
23 return View(customers);
24 }
25
26 [HttpGet]
27 public IActionResult Create()
28 {
29 return View();
30 }
31
32 [HttpPost]
33 public async Task<IActionResult> Create(Customer customer)
34 {
35 if (ModelState.IsValid)
36 {
37 try
38 {
39 _context.Customers.Add(customer);
40 await _context.SaveChangesAsync();
41 TempData["Success"] = "Customer created successfully";
42 return RedirectToAction("Index");
43 }
44 catch
45 {
46 ModelState.AddModelError("", "Failed to create customer");
47 }
48 }
49 return View(customer);
50 }
51
52 [HttpGet]
53 public async Task<IActionResult> Edit(int id)
54 {
55 var customer = await _context.Customers.FindAsync(id);
56 if (customer == null)
57 return NotFound();
58
59 return View(customer);
60 }
61
62 [HttpPost]
63 public async Task<IActionResult> Edit(Customer customer)
64 {
65 if (ModelState.IsValid)
66 {
67 try
68 {
69 _context.Customers.Update(customer);
70 await _context.SaveChangesAsync();
71 TempData["Success"] = "Customer updated successfully";
72 return RedirectToAction("Index");
73 }
74 catch
75 {
76 ModelState.AddModelError("", "Failed to update customer");
77 }
78 }
79 return View(customer);
80 }
81
82 [HttpPost]
83 public async Task<IActionResult> Delete(int id)
84 {
85 try
86 {
87 var customer = await _context.Customers.FindAsync(id);
88 if (customer != null)
89 {
90 _context.Customers.Remove(customer);
91 await _context.SaveChangesAsync();
92 TempData["Success"] = "Customer deleted successfully";
93 }
94 }
95 catch
96 {
97 TempData["Error"] = "Cannot delete customer. It may be in use.";
98 }
99 return RedirectToAction("Index");
100 }
101 }
102}
Note: See TracBrowser for help on using the repository browser.