2017-09-23 115 views
-2

模型的IEnumerable我有一個模型叫Airport,我試圖從控制器傳遞一個IEnumerable<Airport>到視圖顯示,鑑於

public ActionResult Index() 
{ 
    IEnumerable<Airport> airports = GetAirports("https://raw.githubusercontent.com/jbrooksuk/JSON-Airports/master/airports.json"); 
    return View(airports); 
} 

我的目標是在我看來,一個下拉列表顯示機場名稱列表。我無法從控制器變量機場轉移到我的觀點,我不斷收到錯誤:

The name 'airports' does not exist in the current context

這裏是我的觀點

@using WebApplication1.Models 
@using WebApplication1.Controllers 

@model WebApplication1.Models.AirportList 

@{ 
    ViewBag.Title = "Index"; 
} 

<select name="Airports"> 
    @foreach (var link in airports) 
    { 
     <option value="@(link)">@(link)</option> 
    } 
</select> 

這裏使用的代碼是模型Airport我使用

public class Airport 
{ 
    public string iata { get; set; } 
    public decimal lon { get; set; } 
    public string iso { get; set; } 
    public int status { get; set; } 
    public string name { get; set; } 
    public string continent { get; set; } 
    public string type { get; set; } 

    public decimal lat { get; set; } 

    public string size { get; set; } 
} 
+0

你檢查過Json響應嗎? –

回答

2

變化

`@foreach (var link in airports)` 

@foreach (var link in Model) 

@model WebApplication1.Models.AirportList 

這個

@model IEnumerable<WebApplication1.Models.Airport> 
+0

我嘗試了它,現在我得到的錯誤:foreach語句無法對'WebApplication1.Models.AirportList'類型的變量進行操作,因爲'WebApplication1.Models。AirportList」不包含一個公共定義‘的GetEnumerator’ –

+0

你必須要麼執行'IEnumerable'或IEnumerable的''在'AirportList'類,或者乾脆使用的IEnumerable''直接模型(雖然我是不是某些泛型可以用作模型) –

0

嘗試改變airportsModel。在視圖中看不到Controller中的局部變量。你可以,但是,引用Model屬性(初始化爲你傳遞給視圖構造什麼)

另一種方法是通過ViewBag傳遞變量,例如:

public ActionResult Index() 
{ 
    ViewBag.airports = GetAirports("https://raw.githubusercontent.com/jbrooksuk/JSON-Airports/master/airports.json"); 

    return View(); 
} 

那麼在你看來,你可以參考:

@foreach (var link in ViewBag.airports) 

使用Model允許您根據加到屬性模型中的類屬性做這樣的事情模型驗證,並使用ViewBag允許您添加儘可能多的你想要動態的屬性。如果您必須發送機場列表和飛機列表以及有關請求該頁面的登錄用戶的信息,這可能會有所幫助。您可以通過ViewBag傳遞內容,而不是將您的模型增加到令人難以置信的複雜程度。

另一個潛在的問題是您的視圖模型的類型爲WebApplication1.Models.AirportList,但您實際在控制器中傳遞的模型爲IEnumerable<Airport>。我相信只有在您已定義從IEnumerable<Airport>WebApplication1.Models.AirportList的隱式轉換時,這纔會起作用。所以你可能不得不將模型的類更改爲IEnumerable<Airport>