How to pass a string array from a controller to MVC4 views without creating multiple actions?

I am new to mvc4, so please come through, I'm trying to pass a few destination names from the controller to my view. How can I do this without creating more actionresults and objects. I want to create a table with destination names using a string array. Is it possible that 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>
+4
source share
2 answers

, , 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>
+5

, , .

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)

,

0

Source: https://habr.com/ru/post/1534050/


All Articles