您可以創建一個包含Cars
和NumberOfDays
財產
public class MyViewModel
{
public IEnumerable<Car> Cars { get; set; }
public int NumberOfDays { get; set; }
}
然後用它在你的控制器,並把它傳遞給視圖
public ActionResult DayView(int numberDays)
{
MyViewModel model = new MyViewModel();
model.NumberOfDays = numberDays;
model.Cars = ...; // get the car records here
return View(model);
}
,改變你的看法如下
視圖模型類
@model MyViewModel
foreach (Car car in Model.Cars)
{
//other parameters
<p>Full Price</p>:@(car.CostOneDay * Model.NumberOfDays)
}
編輯
如果您想使用@Html.HiddenFor
中的乘數價格,那麼您需要爲您的Car
類添加一個附加屬性。假設CostOneDay
類型是小數,添加FullPrice
屬性與小數類型
public class Car
{
// other properties
public decimal FullPrice { get; set; }
}
然後在控制器
public ActionResult DayView(int numberDays)
{
MyViewModel model = new MyViewModel();
model.NumberOfDays = numberDays;
model.Cars = ...; // get the car records here
foreach (var car in model.Cars)
{
car.FullPrice = car.CostOneDay * model.NumberOfDays;
}
return View(model);
}
設置FullPrice
屬性爲每個汽車記錄,並使用@Html.HiddenFor
像下面
@model MyViewModel
foreach (Car car in Model.Cars)
{
//other parameters
<p>Full Price</p>:@car.FullPrice
@Html.HiddenFor(m => car.FullPrice)
}
你可以定義一個自定義的類,而不是你的模型是IEnumerable有額外的屬性。此時,您只需訪問該屬性。 –
是的,@EricHotinger說。新的類將是一個[ViewModel](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) – Liam
你可以使用[calculated property](http://stackoverflow.com/questions/2030636/c-sharp-read-only-calculated-properties-should-they-be-methods),但我發現這些只會導致更多的問題,而不是他們長期解決的問題。把你的控制器計算成虛擬機 – Liam