2013-12-17 29 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

没有工作。转换到视图变量会引发异常。 –