MVC View-Unable to populate list in the select drop down

Viewed 479

I am trying to implement a simple select drop-down in 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.

    <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.

Below is the HTML generated. enter image description here

Can anyone please help me to figure out what did I miss?

2 Answers

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

@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>
Related