Every time you make a request, a new instance of your controller is created. It processes the request and generates a response, and then that instance is thrown away, along with all of its fields.
The item you add to the
bookings
field in your POST method doesn't survive beyond that single request.
The data needs to be persisted in a database, or some other storage mechanism. For a "toy" application, with no real-world use intended, you might be able to get away with making the list
static
. But you will need to be very careful to manage access from multiple threads.
Once you've added the booking to your persistent storage, redirect the user back to the
Index
action to display the updated list.
You'll probably want to use some sort of repository pattern to make it easier to switch the storage mechanism later:
public interface IBookingRepository
{
List<BookingModel> GetAll();
void Add(BookingModel model);
}
public sealed class DummyBookingRepository : IBookingRepository, IDisposable
{
private readonly ReaderWriterLockSlim _bookingsLock = new ReaderWriterLockSlim();
private readonly List<BookingModel> _bookings = new List<BookingModel>
{
new BookingModel
{
ladestand = 10,
fahrstrecke = 100,
startzeit = new DateTime(2020, 10, 2, 8, 45, 0),
endzeit = new DateTime(2020, 10, 2, 12, 45, 0)
},
new BookingModel
{
ladestand = 65,
fahrstrecke = 340,
startzeit = new DateTime(2020, 05, 3, 9, 45, 0),
endzeit = new DateTime(2020, 05, 3, 11, 45, 0)
},
new BookingModel
{
ladestand = 30,
fahrstrecke = 150,
startzeit = new DateTime(2020, 09, 15, 22, 45, 0),
endzeit = new DateTime(2020, 09, 16, 0, 00, 0)
}
};
public List<BookingModel> GetAll()
{
_bookingsLock.EnterReadLock();
try
{
return new List<BookingModel>(_bookings);
}
finally
{
_bookingsLock.ExitReadLock();
}
}
public void Add(BookingModel model)
{
_bookingsLock.EnterWriteLock();
try
{
_bookings.Add(model);
}
finally
{
_bookingsLock.ExitWriteLock();
}
}
public void Dispose()
{
_bookingsLock.Dispose();
}
}
Register the repository in your app's startup - this dummy repository needs to be a singleton, so that a single instance is used for all requests:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IBookingRepository, DummyBookingRepository>();
...
}
Update your controller to use the repository service:
public class BookingController : Controller
{
public BookingController(IBookingRepository repository)
{
Repository = repository;
}
private IBookingRepository Repository { get; }
public IActionResult Index()
{
List<BookingModel> bookings = Repository.GetBookings();
return View(bookings);
}
[HttpGet]
public IActionResult Create()
{
return View(new BookingModel());
}
[HttpPost]
public IActionResult Create(BookingModel model)
{
Repository.AddBooking(model);
return RedirectToAction(nameof(Index));
}
}