skip to Main Content

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?

3

Answers


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

    Login or Signup to reply.
  2. 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 class="form-control"  asp-for="@WarehouseId" asp-items="@WareHouseNames">
             <option value="0" >Select</option>
    </select>
    
    Login or Signup to reply.
  3. You can make the "public List" into Dictionary and use the key as Id and value as Name from "WareHouse" object.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search