[英]MVC View-Unable to populate list in the select drop down
I am trying to implement a simple select drop-down in razor page .我正在尝试在razor page 中实现一个简单的选择下拉菜单。 I am not sure if I missed anything, the dropdown is not at all populating.
我不确定我是否错过了任何东西,下拉菜单根本没有填充。 Just for demo purpose, I used the hard-coded string values to populate the dropdown.
仅出于演示目的,我使用硬编码的字符串值来填充下拉列表。
I have a list called posts.我有一个名为帖子的列表。
var posts = new List<BlogDetails>();
posts.Add(
new BlogDetails {
Id = 1,
Author = "Charles",
Title = "Finding Charles",
Body = "This is a great blog post",
PostedOn = DateTime.Now
});
ViewBag.listOfItems = posts;
return View();
In the Index.cshtml
I am trying to populate a dropdown using this list.在
Index.cshtml
我尝试使用此列表填充下拉列表。
<select asp-for="Id" asp-items="@(new SelectList(ViewBag.listOfItems, "Id", "Author"))">
<option>Please select one</option>
</select>
I don't know the reason and its not working.我不知道原因,它不起作用。 When I actually looked the HTML generated for this dropdown I am able to see that the list is not processed at all.
当我实际查看为此下拉列表生成的 HTML 时,我能够看到该列表根本没有被处理。
Below is the HTML generated.下面是生成的 HTML。
Can anyone please help me to figure out what did I miss?谁能帮我弄清楚我错过了什么?
The list was not rendering because tag helpers was not enabled.列表未呈现,因为未启用标签助手。 Check if you add the below line in your
_ViewImports.cshtml
directly under your Views folder检查是否直接在 Views 文件夹下的
_ViewImports.cshtml
添加以下行
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Controller控制器
var posts = new List<BlogDetails>();
posts.Add(
new BlogDetails {
Id = 1,
Author = "Charles",
Title = "Finding Charles",
Body = "This is a great blog post",
PostedOn = DateTime.Now
});
ViewBag.listOfItems = new SelectList(posts, "Id", "Author");
return View();
Razor剃刀
@Html.DropDownListFor(model => model.post, (IEnumerable<SelectListItem>)ViewBag.listOfItems, "--Select Post--", new { @class = "form-control" })
Or you can try this或者你可以试试这个
<select>
@foreach(var item in ViewBag.listOfItems)
{
<option value="@item.Id">@item.Author<option>
}
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.