问题描述
模型
public class Car
{
public string Brand { get; set; }
public int Price { get; set; }
public int MaxSpeed(int speed)
{
return speed * 0.8;
}
}
控制器
Car car = new Car();
car.Brand= "ferrari-2020";
car.Price = 50000;
car.MaxSpeed(450);
return View("Index",car);
查看
@model Car
<div class="text-center">
@Model.Brand
@Model.Price
How do I show the value returned from the controller?
@Model.MaximumHiz()
</div>
我可以将方法分配给变量并在View上显示,但是我该怎么做呢?
解决方法
您可以将MaxSpeed创建为具有后备字段的属性
private int _maxSpeed;
public string Brand { get; set; }
public int Price { get; set; }
public int MaxSpeed
{
get => (int) (_maxSpeed * 0.8);
set => _maxSpeed = value;
}
,然后使用car.MaxSpeed = 450;
我不确定,您尝试做的不同,但是原则上您可以为模型分配值并使用它们来呈现视图。 视图本身不知道控制器,因此您只能从模型中渲染值。在屏幕快照中:您缺少调用参数 MaximumSpeed(100)的speed参数。