无法强制转换类型为'System.Data.Entity.DbSet ' [City]'输入'S

本文关键字:DbSet Entity City 输入 Data System 类型 转换 | 更新日期: 2023-09-27 18:06:37

我试图从城市表中加载所有城市并将其显示在客户端的下拉列表中,但它显示了这个错误

无法强制转换类型为'System.Data.Entity.DbSet 1[EVS.Dotnet277.Entities.City]' to type 'System.Collections.Generic.IEnumerable 1[System.Web.Mvc.SelectListItem]'的对象。

行动
[HttpGet]
public ActionResult SignUp()
{
    ViewBag.CityList = _userService.GetAllCities();
    return View();
}

html

<div class="col-md-6">
<label class="select margin-bottom-15">
@Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewBag.CityList, "- Select City -", new { @class = "form-control"})
/label>
</div>

无法强制转换类型为'System.Data.Entity.DbSet ' [City]'输入'S

将代码修改为:

[HttpGet]
public ActionResult SignUp()
{
    ViewBag.CityList =new SelectList( _userService.GetAllCities(),dataValueField, dataTextField);
    return View();
}

查看代码:

<div class="col-md-6">
<label class="select margin-bottom-15">
@Html.DropDownList("City", (SelectList)ViewBag.CityList, "- Select City -", new { @class = "form-control"})
/label>
</div>