您可以创建一个包含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