標題說明了我正在嘗試做的事情。
控制器方法:
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,但我到底該怎么做?
uj5u.com熱心網友回復:
您可以使用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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/311581.html
標籤:C# asp.net-mvc asp.net核心 下拉式菜单
