2016-11-07 23 views
1

我有一個Products表和ProductVM視圖模型,並在ProductVM我想需要從另一個表(Categories)的行的列表,所以我可以顯示在添加新產品時的下拉列表。傳遞模型中另一個表的行的列表

我還沒有這樣做,所以我用ViewBag傳遞到視圖,並作出下拉列表,但我知道我應該通過模型做,但不知道如何。

ProductVM

public class ProductVM 
    { 

     public ProductVM() 
     { 
     } 

     public ProductVM(ProductDTO productDTO) 
     { 
      Id = productDTO.Id; 
      Name = productDTO.Name; 
      Description = productDTO.Description; 
      CategoryId = productDTO.Id; 
     } 

     public int Id { get; set; } 
     public string Name { get; set; } 
     public string Description { get; set; } 
     public int? CategoryId { get; set; } 
    } 

ActionMethod:

public ActionResult AddProduct() 
     { 
      Db db = new Db(); 

      var result = from r in db.Categories 
         select new { r.Name, r.Id }; 

      ViewBag.Categories = new SelectList(db.Categories, "Id", "Name"); 

      return View(); 
     } 

Categories表只是有2列,IdName

而且要明確,我現在的工作,我只是想完全通過模型來完成,而不是使用ViewBag

回答

0

屬性添加到您的視圖模型

public IEnumerable<SelectListItem> Categories { get; set; } 

,並在控制器使用

var model = new ProductVM() 
{ 
    Categories = new SelectList(db.Categories, "Id", "Name" 
}; 
return View(model); 

注意,你也可以使用

Categories = db.Categories.Select(x => new SelectListItem() 
{ 
    Value = x.Id.ToString(), // assumes Id is not typeof string 
    Text = x.Name 
}) 
相關問題