2016-07-20 25 views
-2

我试图用IEnumerable下拉式绑定数据库。但它显示在下面的图像中显示的错误。如何使用MVC5中的dropdownlist绑定数据库?

enter image description here

我的模型(CustomerViewModel)

public Nullable<System.Guid> AreaID { get; set; } 
public string Area { get; set; } 
public IEnumerable<SelectListItem> AreaList { get; set; } 

我的控制器

public ActionResult Create() 
    { 
     CustomerViewModel cvm = new CustomerViewModel(); 
     cvm.AreaList = db.Areas.Where(a => a.IsDeleted == false).Select(a => new SelectListItem() 
     { 
      Value = a.AreaID.ToString(), 
      Text = a.DisplayName 
     }); 
     return View(); 
    } 

我查看代码

@Html.LabelFor(model => model.Area, new { @class = "control-label" }) 
@Html.DropDownListFor(m => m.AreaID, Model.AreaList, "Please select a Area", new { @class = "form-control" }) 
+0

唯一的例外是相当清楚的。 **你认为这意味着什么? –

+0

其实我不明白错误的意思,所以只有我在这里发表steen。 – Susan

回答

1

您的代码工作正常。问题在于,您使用.ToString()方法创建查询,该方法无法转换为DB等效语法。

要使其工作,你需要使用.ToList()选择从DB的项目,之后创建SelectListItem

cvm.AreaList = db.Areas.Where(a => a.IsDeleted == false).ToList().Select(a => new SelectListItem() 
{ 
     Value = a.AreaID.ToString(), 
     Text = a.DisplayName 
}); 
+0

好吧,我有一个尝试 – Susan

+0

我的视图代码中是否有任何错误?因为它在视图代码中显示错误// – Susan

+0

错误是什么?请明确指出 – Catalin

相关问题