2013-12-17 35 views
0

我們正在我們的窗體上填充下拉列表,內置C#ASP.NET MVC 4(有時5)。由於SOF,我建了一個臨時列表,像這樣:填充@ Html.DropDownListFor - 從硬編碼值,從數據庫中的錯誤

/// <summary> 
/// Generate a list of countries. 
/// </summary> 
/// <returns>List(SelectListItem)</returns> 
/// <remarks>Values are from ISO 3166-1 alpha-3</remarks> 
public static List<SelectListItem> Countries() 
{ 
    List<SelectListItem> items = new List<SelectListItem>(); 

    items.Add(new SelectListItem { Text = "United States of America", Value = "USA", Selected = true }); 
    items.Add(new SelectListItem { Text = "Australia", Value = "AUS" }); 
    items.Add(new SelectListItem { Text = "Canada", Value = "CAN" }); 
    items.Add(new SelectListItem { Text = "Mexico", Value = "MEX" }); 
    items.Add(new SelectListItem { Text = "United Kingdom", Value = "GBR" }); 

    return items; 
} 

然後通過這個入ViewBag:

ViewBag.CountryList = SelectLists.Countries(); 

,並呈現它:

@Html.DropDownListFor(model=>model.country_code, 
    (List<SelectListItem>)ViewBag.CountryList) 

這部分的所有隻是工作精細。

現在團隊正在實現代碼來從數據庫中檢索查找,而不是從模擬數據中檢索,而且事情並不好。我們的業務對象方法接受一個查找類型,在這種情況下, 「國家」,而應返回List<SelectListItem>

控制器:

List<SelectListItem> countryList = GetLookupData("Country"); 
ViewBag.CountryList = countryList; 

型號:

public static List<SelectListItem> GetLookupData(string lookupType) 
{ 
    MPPEntities dbContext = new MPPEntities(); 
    var query = (from c in dbContext.SystemLookups 
        where c.lookup_type == lookupType 
        orderby c.order_by 
        select new SelectListItem { Text = c.name, Value = c.value }) 
        .ToList<SelectListItem>(); 

    return (List<SelectListItem>)query; 
} 

雖然我們正在調試的LINQ ,query包含正確的數據。但是當調試器返回到控制器時,countryList因「無法評估表達式」而失敗。當然,這個觀點本身就失敗了。

基於模擬列表工作的觀察結果以及真實列表包含正確數據的情況,我推斷出失敗點是從泛型集合到List<SelectListItem>的轉換。什麼是正確的方式來轉換列表類型?

ETA:CSHTML文件中的錯誤爲: 「RuntimeBinderInternalCompilerException未被用戶代碼處理。」這與下面推薦的更少的演員陣容有關。

回答

2

你似乎使許多無用的鑄件...

你能嘗試

public static List<SelectListItem> GetLookupData(string lookupType) 
    { 
     MPPEntities dbContext = new MPPEntities(); 
     return (from c in dbContext.SystemLookups 
        where c.lookup_type == lookupType 
        orderby c.order_by 
        select new SelectListItem { Text = c.name, Value = c.value }) 
        .ToList(); 
    } 

你可以試試在你看來

@{ 
    var contryCodes = (IEnumerable<SelectListItem>)ViewBag.CountryList; 
} 

@Html.DropDownListFor(model=>model.country_code, 
    countryCodes) 

因爲它看起來像一個動態問題(ViewBag)...

+0

不,我得到了和以前一樣的'RuntimeBinderInternalCompilerException'。 –

+0

@CodeswithHammer看編輯也許? –

+0

沒有工作。轉換到視圖變量會引發異常。 –