我是mvc4的新用户,所以请放心,我试图将多个目的地名称从控制器传递到我的视图。如何在不创建更多动作结果和对象的情况下执行此操作。我想使用字符串数组创建一个目标名称的表。这可能是任何帮助将不胜感激。提前谢谢。
Controller:
public ActionResult Destinations()
{
string[] arrivalAirport = new string[4] { "london", "paris", "berlin",
"manchester" };
Destination dest = new Destination();
dest.arrivalName = arrivalAirport[2];
return View(dest);
}
Model:
public class Destination
{
public string arrivalName { get; set; }
public string arrivalCode { get; set; }
}
View:
@model Flight.Models.Destination
@{
ViewBag.Title = "Destinations";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table>
<tr>
<td>@Html.Label("Arrival Name")</td>
<td>@Model.arrivalName</td>
</tr>
</table>
答案 0 :(得分:5)
您的问题的措辞非常混乱,但听起来您想要将多个Destination对象传递给您的视图。如果是这种情况,只需将多个目标对象传递给您的视图。
控制器:
public ActionResult Destinations()
{
string[] arrivalAirport = new string[4] { "london", "paris", "berlin",
"manchester" };
var airports = new List<Destination>();
foreach( var airport in arrivalAirport )
{
airports.Add( new Destination() { arrivalName = airport } );
}
return View(airports);
}
查看:
@model List<Flight.Models.Destination>
<table>
@foreach( var dest in Model )
{
<tr>
<td>Arrival Name</td>
<td>@dest.arrivalName</td>
</tr>
}
</table>
答案 1 :(得分:1)
使用视图模型,您可以在其中定义视图所需的任何信息
public class ViewModel{
public List<string> Airports { get; set; }
public Destination destination { get; set; }
etc...
}
然后在您的控制器上填充视图模型
public ActionResult Index(){
ViewModel vm = new ViewModel();
var db = //query your database
vm.Destination.arrivalName = db.ArrivalName;
etc...
return View(vm);
}
并在您的观点
@model ViewModel
@Html.TextBoxFor(x => x.Destination.arrivalName)
希望这会有所帮助