Displaying data in a SelectList in ASP.NET Core

EB. picture EB. · Oct 3, 2016 · Viewed 34.1k times · Source

I've tried a few different approaches. I'm not sure why but my SelectList/DropDown is empty. It shows no data. I'm not sure where I am going wrong.

I have an ASP.NET Core App. Entity Framework Core. Db First. I am using a repository pattern.

Here is my Model Class

public partial class Commodity
{
    public Guid Oid { get; set; }
    public string Code { get; set; }
}

This is my Interface:

interface ICommodityRepository
{
    IEnumerable<Commodity> GetAll();
}

My Repository:

public class CommodityRepository : ICommodityRepository
{
    private ltgwarehouseContext context;

    public CommodityRepository()
    { }

    public IEnumerable<Commodity> GetAll()
    {
        return context.Commodity.ToList();
    }
}

My Controller:

public class CommoditiesController : Controller
{
    static readonly CommodityRepository commodities = new CommodityRepository();

    public CommoditiesController(CommodityRepository commodities)
    { }

    // GET: /<controller>/
    public IEnumerable<Commodity> CommoditiesList()
    {
        return commodities.GetAll();
    }
}

This is my View/HTML Markup:

@model Lansing.BasisMap.Domain.Models.Commodity

Answer

Dai picture Dai · Oct 3, 2016

(I'm not too familiar with the Tag Helper syntax in ASP.NET Core, but I'll give it a shot, anyone please correct me if I'm wrong)

  • The asp-for="" attribute does not need the @ prefix because it is not Razor code, the attribute value is already handled by ASP.NET's parser - you only need it if you're using C# syntax that is ambiguous with HTML (e.g. double-quotes).
  • The asp-controller and asp-action attributes do not apply to <select>
  • You are not providing any options to your <select>, use the asp-items attribute and provide IEnumerable<SelectListItem> or a SelectList instance. This can be passed in through your ViewModel or (my preference) through ViewData (or ViewBag).

Assuming it's ViewData, then:

public ActionResult YourControllerAction() {

    // stuff
    this.ViewData["items"] = commodities
        .GetAll()
        .Select( c => new SelectListItem() { Text = c.Code, Value = c.Oid.ToString() } )
        .ToList();

    // stuff
    return this.View( viewModel );
}

And use it in view like this:

<select asp-for="Model.Code" asp-items="@ViewData["items"]" />

There's a lot more examples in this QA posting: Select Tag Helper in ASP.NET Core MVC