Home > Back-end >  How to turn a EF Core/LINQ query into a List<SelectList>?
How to turn a EF Core/LINQ query into a List<SelectList>?

Time:06-24

I have the following Category Model:

public class CategoryDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<SelectList> WarehouseNames { get; set; }
}

Warehouse Model:

public class Warehouse
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public int MaxCapacity { get; set; }   
}

I want to get all the Warehouse.Id and Warehouse.Name in my database and store them in the CategoryDTO.WarehouseNames (value: Id, Text: Name) so I can display them in a dropdown list. Does anybody know how can I do this?

CodePudding user response:

fix Dto to List, and maybe you need to add a WarehouseId too???

public class CategoryDTO
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int WarehouseId { get; set; } //????
    public List<SelectListItem> WarehouseNames { get; set; }
}

in you action should be something like this

var model= new CategoryDTO();

var wareHouseNames = context.Set<Warehouse>()
                    .Select ( i=>  new SelectListItem {
                     Text = i.Name,
                     Value = i.Id
                    }).ToList();
model.WareHouseNames = wareHouseNames ;

return View(model)

and view

@model CategoryDTO


<select   asp-for="@WarehouseId" asp-items="@WareHouseNames">
         <option value="0" >Select</option>
</select>

CodePudding user response:

I think you want to remove the WarehouseNames property from the CategoryDTO type completely, and instead of populating one CategoryDTO object populate a List<CategoryDTO> or (even better!) IEnumerable<CategoryDTO>.

Then you will be able to map these CategoryDTO items to a dropdown list/HTML Select entity. Exactly what that looks like, though, depends on information not yet in your question.

  • Related