【问题标题】:ASP.Net Core 5 MVC Populate a drop down list with Database recordsASP.Net Core 5 MVC 用数据库记录填充下拉列表
【发布时间】:2021-10-06 19:58:28
【问题描述】:

标题说明了我正在尝试做的事情。

控制器方法:

public IActionResult Create()
        {
            IEnumerable<string> hList = from char s in _context.NR_Users select s.ToString();

            List < NR_User > hUsers = new List<NR_User>();
            hUsers = (from c in _context.NR_Users select c).ToList();
            hUsers.Insert(0, new NR_User { ID = 0, Name = "Select" });
            ViewBag.historyUsers = hUsers;

            List<SelectListItem> options = new()
            {
                new SelectListItem { Value = "True", Text = "Yes" },
                new SelectListItem { Value = "False", Text = "No" }
            };
            ViewBag.options = options;
            return View();
        }

查看:

<div class="form-group col-md-4">
                    <label class="control-label">History PM</label>
                    <select asp-for="History_PM" name="History_PM" class="form-control" asp-items="@ViewBag.historyUsers"></select>
                    <span asp-validation-for="History_PM" class="text-danger"></span>
                </div>

但是当我运行应用程序并导航到创建页面时,我收到了这个错误:

RuntimeBinderException: Cannot implicitly convert type 'System.Collections.Generic.List<EnvApp.Models.DB.NR_User>' to 'System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>'. An explicit conversion exists (are you missing a cast?)

我知道它不能将列表隐式转换为 IEnumerable,但我该怎么做呢?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core drop-down-menu


    【解决方案1】:

    您可以使用SelectList 类转换列表。

    尝试替换

    <select asp-for="History_PM" name="History_PM" class="form-control" asp-items="@ViewBag.historyUsers"></select>
    

    <select asp-for="History_PM" name="History_PM" class="form-control" asp-items="@(new SelectList(ViewBag.historyUsers, "ID", "Name"))"></select>
    

    【讨论】:

    • 成功了,谢谢你,我不知道!
    猜你喜欢
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    相关资源
    最近更新 更多