问题
I am new to mvc4 so please go easy, i am trying to pass multiple names of destinations from the controller to my view. How can i do this without creating more actionresults and objects. I want to create a table with the destination names using a string array. Is this possible any help would be appreciated. Thank You in advance.
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>
回答1:
The wording of your question is very confusing, but it sounds like you want to pass multiple Destination objects to your view. If that's the case, just pass multiple destination objects to your view.
Controller:
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);
}
View:
@model List<Flight.Models.Destination>
<table>
@foreach( var dest in Model )
{
<tr>
<td>Arrival Name</td>
<td>@dest.arrivalName</td>
</tr>
}
</table>
回答2:
use a view model where you can define whatever information you need for your view
public class ViewModel{
public List<string> Airports { get; set; }
public Destination destination { get; set; }
etc...
}
then on your controller you populate the view model
public ActionResult Index(){
ViewModel vm = new ViewModel();
var db = //query your database
vm.Destination.arrivalName = db.ArrivalName;
etc...
return View(vm);
}
and on your view
@model ViewModel
@Html.TextBoxFor(x => x.Destination.arrivalName)
Hopefully this helps
来源:https://stackoverflow.com/questions/22732912/how-to-pass-a-string-array-from-controller-to-the-view-mvc4-without-creating-mul