繁体   English   中英

控制器错误“ Microsoft.AspNetCore.Mvc.Rendering.SelectListItem”中的MVC核心SelectList下拉列表

[英]MVC Core SelectList Dropdown in Controller Error “Microsoft.AspNetCore.Mvc.Rendering.SelectListItem”

我想在MVC中创建一个SelectList下拉列表。

我更喜欢选择列表在存储库中,而不是在控制器中。 如何调用存储库,甚至不引用模型中字段的名称。 我唯一要参考的是存储库。

我收到此“ Microsoft.AspNetCore.Mvc.Rendering.SelectListItem”的错误消息此资源尚无帮助: 为什么我的DropDownList中出现“ System.Web.Mvc.SelectListItem”?

我正在网上阅读许多示例,这是原始代码,

原始代码:

ViewData["ProductTypeId"] = new SelectList(_context.ProductType, "ProductName", "ProductDescription");

我正在尝试使代码像这样工作:

收到错误:“ Microsoft.AspNetCore.Mvc.Rendering.SelectListItem”

 ViewData["ProductTypeId"] = new SelectList(_producttyperepository.GetAllLookupKey());

    public IEnumerable<SelectListItem> GetAllLookupKey()
    {

       return  (from ptin _context.ProductType pt
                       select new SelectListItem
                       {
                           Value = pt.ProductTypeName,
                           Text = pt.ProductDescription
                       });

    }

        <div class="form-group">
            <label asp-for="ProductType" class="control-label"></label>
            <select asp-for="ProductType" class="form-control" asp-items="ViewBag.ProductTypeId"></select>
            <span asp-validation-for="ProductType" class="text-danger"></span>
        </div>

您当前的GetAllLookupKey无法编译! 使用这个版本。

public IEnumerable<SelectListItem> GetAllLookupKey()
{
    return _context.ProductType.Select( pt=>new SelectListItem
    {
        Value = pt.ProductTypeName,
        Text = pt.ProductDescription
    }).ToList();
}

同样,也无需创建第二个SelectList 您的GetAllLookupKey方法返回SelectListItem的集合,您可以将其设置为ViewData。

 ViewData["ProductTypeId"] = _producttyperepository.GetAllLookupKey();

SelectListItem类在名称空间Microsoft.AspNetCore.Mvc.Rendering;定义Microsoft.AspNetCore.Mvc.Rendering; 因此,请确保您具有在类中包含该名称空间的using语句。

using Microsoft.AspNetCore.Mvc.Rendering;

如果该项目与具有Controllers的项目不在同一项目中。 确保您的项目引用了具有此名称空间和类的程序集。

虽然这可能会解决我们的问题,但SelectListItem是一个类,可以表示更多有关UI层的问题。 恕我直言 ,您不应该让您的存储库返回该信息。 让您的存储库返回更多通用数据(例如:ProductType列表),并让您的UI层代码(控制器操作/ UI服务层等)从此ProductType列表中生成SelectListItem对象的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM