I am creating a web app using C# MVC. I created a model named Trip.cs
with properties as below:
public int ID {get; set;}
public string Destination {get; set;}
public DateTime DepartureDate {get; set;}
public string MeetPlace {get; set;}
public int NumberOfSeats {get; set;}
public virtual ApplicationUser User { get; set; }
public string UserId { get; set; }
I created another model called ReservedTrip.cs
identical with Trip.cs
with the same properties. What I do is when the logged user clicks on the Actionlink
named "Reserve Trip", I save this "Trip" to the ReservedTrip.cs
and I decrease the number of property NumberOfSeats
with 1. So in other words I copy this "Trip" data from Trip.cs
to ReservedTrip.cs
. The problem is when I display in a view the data from model Trip.cs
the number of NumberOfSeats
changes, but in the model ReservedTrip.cs
the property NumberOfSeats
doesn't change. So I want the changes of property NumberOfSeats
of model Trip.cs to change in the property NumberOfSeats
to be changed with the same value.
Can anyone help me?
From a design standpoint, it is better to not have a copy of any table. A good design for this situation can be something like this.
public class Trip
{
public int ID {get; set;}
public string Destination {get; set;}
public DateTime DepartureDate {get; set;}
public string MeetPlace {get; set;}
public int NumberOfSeats {get; set;}
public int CreatedByUserID {get; set;}
public virtual ApplicationUser CreatedByUser {get; set;}
public virtual ICollection<TripReservation> Reservations {get;set;}
}
public class TripReservation
{
public int ID {get; set;}
public int TripID {get; set;}
public int UserID {get; set;}
public virtual Trip Trip {get; set;}
public virtual ApplicationUser User {get; set;}
}
then in your controller you can construct a view model with the number of seats available being
numberOfSeatsAvailable = trip.NumberOfSeats - trip.Reservations.Count();
If a reservation can reserve more than 1 seat, you can sum that from all reservations for that trip.
Example: ViewModel
public class TripReservationsViewModel
{
public Trip Trip { get; set; }
public int NumberOfSeatsAvailable { get; set; }
}
Example: Controller
public ActionResult TripDetails(int id)
{
var trip = db.Trips.FirstOrDefault(trip => trip.ID == id);
if (trip == null)
{
// Trip does not exist,
// Redirect the user to the trips home page
//
return RedirectToAction("Index");
}
var viewModel = new TripReservationsViewModel();
viewModel.Trip = trip;
viewModel.NumberOfSeatsAvailable = trip.NumberOfSeats - trip.Reservations.Count();
return View(viewModel);
}
Example: View
@model TripReservationsViewModel
<h1>Trip Details</h1>
<p>Seats available: @Model.NumberOfSeatsAvailable</p>
etc...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.