【问题标题】:MVC Core SelectList Dropdown in Controller Error "Microsoft.AspNetCore.Mvc.Rendering.SelectListItem"控制器错误“Microsoft.AspNetCore.Mvc.Rendering.SelectListItem”中的 MVC Core SelectList 下拉列表
【发布时间】:2018-05-24 21:27:44
【问题描述】:

我想在 MVC 中创建一个 SelectList Dropdown。

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

我收到此“Microsoft.AspNetCore.Mvc.Rendering.SelectListItem”的错误 此资源还没有帮助: Why I am getting "System.Web.Mvc.SelectListItem" in my DropDownList?

我在网上阅读了很多例子,这是原始代码,

原始代码:

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>

【问题讨论】:

  • 嗯,试试ViewData["ProductTypeId"] = _producttyperepository.GetAllLookupKey();
  • 命名令人困惑。 POCO 实体命名为ProductType。视图模型是否有属性名称ProductType
  • 已尝试“在编译处理此请求所需的资源期间发生错误。请查看以下具体错误详细信息并适当修改您的源代码。”它最初与 Viewbag 合作,出于某种原因,将重新审视
  • 是的,Win正确,viewmodel也是产品类型,我要重命名这个,3个月前开始编程

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

您当前的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; 中定义,因此请确保您有一个 using 语句,该语句在您的类中包含该命名空间。

using Microsoft.AspNetCore.Mvc.Rendering;

如果这是在与具有控制器的项目不同的项目中。确保您的项目具有对具有此命名空间和类的程序集的引用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    相关资源
    最近更新 更多