I have a view that produ" /> I have a view that produ" /> I have a view that produ"/>

Dotnet core -- How do I convert a Queryable<string> to SelectList for use in a drop down?

401 views Asked by At
 <TargetFramework>netcoreapp3.1</TargetFramework>
 <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.3" />

I have a view that produces a list of unique towns in alphabetical order.

Model:

public class dgTown
    {
        [Key]
        public string town { get; set; }
    }

View Model:

public List<SelectList> dgTowns { get; set; }
public string TownSelection { get; set; }

Database context:

public DbSet<dgTown> vtown { get; set; }

Controller:

var townQuery = _context.vtown.Select(t => t.town);

How do I convert the resulting EntityQueryable to a SelectList so the drop down can use it?

 <select asp-for="TownSelection" asp-items="Model.dgTowns">
   <option value="">All</option>
 </select>
2

There are 2 answers

0
Ashiquzzaman On

Please read the microsoft documentation about dropdown.

Example:

View Model:

public class YourModel{
  public List<SelectListItem> dgTowns { get; set; }
  public string TownSelection { get; set; }
}

Controller:

  public Task<IActionResult> YourActin()
        {
            var model = new YourModel();
            model.dgTowns=await _context.vtown
                         .Select(t => new SelectListItem 
                           { 
                             Text = t.town,
                             Value =t.town 
                            })
                         .ToListAsync();
            return View(model);
        }

View:

<select asp-for="TownSelection" asp-items="Model.dgTowns" class="form-control"></select>
0
WCS On

Thanks for the response! Here is what I found to work: 1. Remove List in the model,

public SelectList Town { get; set; }
  1. In the controller, take the results from the query and cast it as IQueryable <string>`
 public async Task<IActionResult> Meetings()
        {
           ...
           IQueryable<string> townQuery = from lst in _context.vtown
                                           orderby lst.town
                                           select lst.town;
          ...
          // Load the view model
          var dgListView = new pgListView
            {   
              ...
              Town = new SelectList(await townQuery.ToListAsync()),
               DgLists = await list.ToListAsync()
            };

Now it can be used in the razor page.

Town:
<select asp-for="TownSelection" asp-items="Model.Town">
   <option value="">All</option>
</select>