正在填充@Html.DropDownListFor--硬编码值正常,数据库错误

本文关键字:数据库 错误 编码值 填充 @Html DropDownListFor-- | 更新日期: 2024-10-18 16:56:08

我们在C#ASP中构建的表单上填充下拉列表。NET MVC 4(有时是5)。多亏了SOF,我建立了一个临时列表,如下所示:

/// <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 )

这部分工作得很好。

现在,团队正在实现从数据库而不是从模拟数据中检索查找的代码,但情况并不好。我们的业务对象方法接受查找类型,在本例中为"Country",并且应该返回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。"下面建议使用较少的强制转换。

正在填充@Html.DropDownListFor--硬编码值正常,数据库错误

你似乎做了很多无用的铸件。。。

你能试试吗

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)的问题。。。