Files
csharp-uebung/FahrzeugeMVC/Controllers/FahrzeugController.cs
2025-04-30 01:10:55 +02:00

71 lines
1.9 KiB
C#

using FahrzeugDatenBank;
using FahrzeugeMVC.Models;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
namespace FahrzeugeMVC.Controllers;
public class FahrzeugController : Controller
{
public IActionResult Index(string searchTerm)
{
string connectionString = this.GetConnectionString();
var repository = new FahrzeugRepository(connectionString);
List<FahrzeugDTO> fahrzeugs;
if (!string.IsNullOrEmpty(searchTerm))
{
fahrzeugs = repository.SucheFahrzeuge(searchTerm);
}
else
{
fahrzeugs = repository.HoleAlleFahrzeuge();
}
var model = new FahrzeugListeModel(fahrzeugs);
return View(model);
}
public string GetConnectionString()
{
return "Server=localhost;User ID=admin;Password=admin;Database=FahrzeugDB";
}
[HttpGet]
public IActionResult Einfuegen()
{
var model = new FahrzeugEinfugenModel();
return View(model);
}
[HttpPost]
public IActionResult Einfuegen(FahrzeugEinfugenModel model)
{
if (ModelState.IsValid && !string.IsNullOrEmpty(model.Name) && !string.IsNullOrEmpty(model.Type))
{
string connectionString = this.GetConnectionString();
var repository = new FahrzeugRepository(connectionString);
repository.FuegeFahrzeugEin(model.Name, model.Type);
return RedirectToAction(nameof(Index));
}
else
{
return View(model);
}
}
[HttpGet]
public IActionResult Loesche(int id)
{
if (ModelState.IsValid)
{
string connectionString = this.GetConnectionString();
var repository = new FahrzeugRepository(connectionString);
repository.LoescheFahrzeug(id);
}
return RedirectToAction(nameof(Index));
}
}