AgentsController.cs (3633B)
1 using Microsoft.AspNetCore.Mvc; 2 using MVC_databaskonstruktion.Models; 3 using MySql.Data.MySqlClient; 4 using System.Diagnostics; 5 6 namespace MVC_databaskonstruktion.Controllers 7 { 8 public class AgentsController : Controller 9 { 10 private readonly IConfiguration _configuration; 11 private AgentsModel _agentsModel { get; set; } 12 13 public AgentsController(IConfiguration configuration) 14 { 15 this._configuration = configuration; 16 _agentsModel = new AgentsModel(_configuration); 17 } 18 19 public IActionResult Index() 20 { 21 MapTables(); 22 MapDropdowns(); 23 24 return View(); 25 } 26 27 public IActionResult Search(string searchQuery) 28 { 29 ViewBag.Agents = _agentsModel.SearchAgents(searchQuery); 30 31 return View("Search"); 32 } 33 34 public IActionResult Create( 35 string CodeName, 36 string FirstName, 37 string LastName, 38 decimal Salary, 39 bool IsFieldAgent, 40 bool IsGroupLeader, 41 bool IsManager) 42 { 43 Trace.WriteLine("Running function: Create new Agent." + 44 "Received parameters: " + 45 CodeName + FirstName + LastName + Salary + IsFieldAgent + IsGroupLeader + IsManager); 46 47 try 48 { 49 _agentsModel.CreateAgent(CodeName, FirstName, LastName, Salary, IsFieldAgent, IsGroupLeader, IsManager); 50 } 51 catch (MySqlException e) 52 { 53 switch (e.Number) 54 { 55 case 1062: 56 TempData["ErrorMessage"] = "CodeName already exists!"; 57 break; 58 case 1406: 59 TempData["ErrorMessage"] = "Data too long!"; 60 break; 61 case 3819: 62 TempData["ErrorMessage"] = "Invalid Data!"; 63 break; 64 default: 65 TempData["ErrorMessage"] = $"Something went wrong: {e.Number}"; 66 break; 67 } 68 } 69 70 return RedirectToAction("Index"); 71 } 72 73 public IActionResult FieldAgentDetails(string CodeName) 74 { 75 ViewBag.AgentOperations = _agentsModel.GetAgentOperations(CodeName); 76 return View(); 77 } 78 79 public IActionResult Delete(string table, string CodeName) 80 { 81 try 82 { 83 _agentsModel.DeleteAgent(table, CodeName); 84 } 85 catch (MySqlException e) 86 { 87 switch (e.Number) 88 { 89 case 1451: 90 TempData["ErrorMessage"] = "Foreign Key Constraint Failed!"; 91 break; 92 case 1452: 93 TempData["ErrorMessage"] = "Foreign Key Constraint Failed!"; 94 break; 95 default: 96 TempData["ErrorMessage"] = $"Something went wrong: {e.Number}"; 97 break; 98 } 99 } 100 101 return RedirectToAction("Index"); 102 } 103 104 private void MapTables() 105 { 106 ViewBag.FieldAgents = _agentsModel.GetFieldAgents(); 107 ViewBag.GroupLeaders = _agentsModel.GetGroupLeaders(); 108 ViewBag.Managers = _agentsModel.GetManagers(); 109 } 110 111 public void MapDropdowns() 112 { 113 ViewBag.CreateAgentModal = _agentsModel.CreateAgentModal(); 114 } 115 } 116 }