我的目标是从数据库中获取位置列表(即" sites")并使用ViewComponent在_Layout的下拉列表(html select元素)中显示它们,但是我收到以下错误:
"无法隐式转换类型 ' System.Collections.Generic.List'至 ' Microsoft.AspNetCore.Mvc.IViewComponentResult&#39 ;.一个明确的 转换是否存在(您是否错过了演员表?)"
查看组件类[SiteID.cs] (PortalContext是我的DbContext)
namespace XX.Views.Shared.Components
{
[ViewComponent(Name = "SiteIDsDropDown")]
public class SiteIDsDropDownViewComponent : ViewComponent
{
private ILogger logger;
private PortalContext context;
public IViewComponentResult Invoke(ILogger<SecureController> logger, PortalContext context)
{
var _logger = logger;
var _context = context;
var results = (from s in _context.Sites
select new SiteViewModel
{
ID = s.ID,
Description = s.Description
}).ToList();
return results;
}
}
查看组件部分视图[〜/ Views / Shared / Component / SiteIDsDropDownViewComponent / default.cshtml]
@model IEnumerable<XX.ViewModels.SiteIDViewModel>
<select>
<option>Please select and item</option>
@foreach (var item in Model)
{
<option>@item.ID</option>
}
</select>
答案 0 :(得分:0)
返回结果应该是View(结果),所以相应地改变你的方法。
public IViewComponentResult Invoke(ILogger<SecureController> logger, PortalContext context)
{
var _logger = logger;
var _context = context;
var results = (from s in _context.Sites
select new SiteViewModel
{
ID = s.ID,
Description = s.Description
}).ToList();
return View(results);
}