请看下面的代码。我正在尝试通过使用 EF 数据库优先方法创建一个下拉列表,并为 DI 实现 Ninject。我对这些概念很陌生,我不知道我做错了什么。任何帮助将不胜感激 - 谢谢。
以下是我的错误:
无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.IEnumerable”。
下面是我的控制器
public class CitiesController: Controller
{
private readonly ICitiesRepository repository;
public CitiesController(ICitiesRepository repository)
{
this.repository = repository;
}
public ActionResult Index()
{
var model = new Models.MyViewModel();
model.Cities = this
.repository
.GetAll()
.ToList()
.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return Content("Thanks for selecting city: " + model.SelectedCityId);
}
}
我在模型文件夹下有以下三个类(CityDTO、MyViewModel、MyModel)。
CityDTO.cs
public class CityDTO
{
public string CityId { get; set; }
public string CityName { get; set; }
}
MyViewModel.cs
public class MyViewModel
{
public string SelectedCityId { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
我的模型.cs
public interface ICitiesRepository
{
IEnumerable<City> GetAll();
}
public class CitiesRepositoryEF: ICitiesRepository
{
public IEnumerable<City> GetAll()
{
using (var ctx = new LocationEntities())
{
return ctx.usp_GetAllCities().ToList();
}
}
}
GlobalAsax.cs
protected void Application_Start()
{
App_Start.NinjectWebCommon.Start();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
App_Start/NinjectWebCommon.cs
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<Models.ICitiesRepository>().To<Models.CitiesRepositoryEF>();
}
以下是我的观点:
@model TestApp.Models.MyViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(x=>x.SelectedCityID, Model.Cities, "Select City")
<button type = "submit">OK</button>
}