我有一个视图,我在其中创建新对象并将其传递给另一个视图:
cs
我在“ChooseCars”中的:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,carID,DateFrom,DateTo,UserID")] Reservation reservation)
{
if (ModelState.IsValid)
{
return RedirectToAction("ChooseCars",reservation);
}
return View(reservation);
}
并在那个“ChooseCars”视图中我用没有保留的汽车列表填充表格。现在我需要以某种方式将该预订和选择的汽车(通过id)传递给我创建新“预订”的某种方法包含carId的对象。
最好的方法是什么?
我写了一个方法,但我不知道如何将这些参数路由到它:
public ActionResult ChooseCars(Reservation reservation)
{
var reservations = db.Reservations.ToList();
var cars = db.Cars.ToList();
var reservationsResult = reservations.Where(res => res.DateFrom <= reservation.DateFrom && res.DateTo >= reservation.DateTo);
if (reservationsResult != null)
{
emptyCars = cars.Where(c => !reservationsResult.Any(y => y.carID == c.ID));
cars = emptyCars.ToList();
}
return View(cars);
}
外观如何:
答案 0 :(得分:1)
您的编辑数据,因此首先要创建一个表示您想要在视图中编辑/显示的视图模型。在您的情况下,您需要开始和结束日期,Car
和所选汽车的集合。
public class ReservationVM // add validation and display attributes as appropriate
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int? SelectedCar { get; set; }
public IEnumerable<Car> AvailableCars { get; set; }
}
你的控制器方法将是
[HttpGet]
public ActionResult Create()
{
ReservationVM model = new ReservationVM();
return View(model);
}
[HttpPost]
public ActionResult Create(ReservationVM model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var availableCars = ... // your query to load the collection of cars basd on the dates
if (!availableCars.Any())
{
ModelState.AddModelError("", "There are no cars available for these dates");
return View(model);
}
model.AvailableCars = availableCars;
return View("SelectCar", model);
}
[HttpPost]
public ActionResult Confirm(ReservationVM model)
{
// Initialize new Reservation, save and redirect
Reservation reservation = new Reservation()
{
StartDate = model.StartDate,
EndDate = model.EndDate,
CarId = model.SelectedCar.Value,
UserId = ... // current user?
};
db.Reservations.Add(reservation);
db.SaveChanges();
return RedirectToAction(....);`
}
视图将是
Create.cshtml
@model ReservationVM
...
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.StartDate)
@Html.TextBoxFor(m => m.EndDate)
<input type="submit" value="Next" />
}
SelectCar.cshtml
@model ReservationVM
....
<table>
@foreach(var car in Model.AvailableCars)
{
<tr>
<td>@car.Make</td>
<td>@car.Model</td>
....
<td>
@using (Html.BeginForm("Confirm", "Home", new { StartDate = Model.StartDate, EndDate = Model.EndDate, SelectedCar = car.ID }))
{
<input type="submit" value="Reserve" />
}
</td>
</tr>
}
</table>