我希望这个完整的例子对你有所帮助。
这是包含出租车信息的TaxiInfo类:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
我们还有一个便利模型,它包含一个TaxiInfo (s)列表:
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
现在在 home 控制器中,我们有默认的Index操作,对于这个示例,它会创建两个出租车司机并将他们添加到 TaxiInfo 中包含的列表中:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
视图的代码如下:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: $@TaxiInfo.Fare</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
ActionLink负责重定向到Home控制器的预订操作(并传入适当的 TaxiInfo 对象),其定义如下:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
这将返回以下视图:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for $@Model.Fare</h1>
视觉之旅: