5

I'm working in .Net Core VS2017

and trying to populate my dropdown with data from the model. For this purpose I declared my select list as

<select class="form-control" asp-for="TicketTypes" asp-items="@(new SelectList(Model.TicketTypes,"Id","Name"))"></select>

It is loading the data correctly but it automatically adds the multiple attribute to it. How to stop this because I need to show this in dropdown

Nouman Bhatti
  • 1,341
  • 6
  • 28
  • 54

1 Answers1

5

So it turns out the select tag helper will automatically generate a multi-select if the property specified in the asp-for attribute is an IEnumerable.

public IEnumerable<Models.TicketTypeList> TicketTypes { get; set; }

So I changed the code and stored the data in ViewBag as SelectList by changing the code in controller to

var ticketTypes = _context
                .TicketType
                .Where(w => w.Deleted == false)
                .Select(s => new {
                                                    id = s.Id,
                                                    Name = s.Name
                    }).OrderBy(o=>o.Name).ToList();

ViewBag.ticketTypeList = new SelectList(ticketTypes, "id", "Name");

and then in the view changed the code to

@Html.DropDownList("TicketTypes",ViewBag.ticketTypeList as SelectList, new { @class = "form-control" })
Nouman Bhatti
  • 1,341
  • 6
  • 28
  • 54