2012-08-12 60 views
1

我是新來的MVC3(這就是爲什麼我買了一本書,這就是爲什麼我現在有這個問題!),所以道歉,如果有一個明顯的答案這個!將多個模型傳遞給使用MVC3和Ninject的視圖

我正在關注一個在MVC3中構建購物車的簡單示例。本書提倡使用Ninject進行依賴注入,而我也是新手。對於一個模型,在這種情況下,產品看起來似乎很簡單,但在此基礎上,我正努力添加第二個模型,並在顯示產品模型的相同視圖中顯示此模型。我試過使用視圖模型,但我發現所有的例子都包含幾個類到一個模型中,我不能完全弄清楚如何在我的代碼中實現它。

類:

public class Product 
{ 
    public int ProductId {get;set;} 
    public string Name {get;set;} 
} 

摘要庫:

public interface IProductRepository 
{ 
    IQueryable<Product> Products {get;} 
} 

類到模型數據庫關聯:

public class EFDbContext : DbContext 
{ 
    public DbSet<Product> Products {get;set;} 
} 

產品信息庫,它實現的抽象接口:

public class EFProductRepository : IProductRepository 
{ 
    private EFDbContext context = new EFDbContext(); 

    public IQueryable<Product> Products 
    { 
     get {return context.Products;} 
    } 
} 

Ninject將IProductRepository綁定到ControllerFactory類中的EFProductRepository。

控制器:

public class ProductController : Controller 
{ 
    private IProductRepository repository; 

    public ProductController(IProductRepository productRepository) 
    { 
     repository = productRepository; 
    } 

    public ViewResult List() 
    { 
     return View(repository.Products); 
    } 
} 

我的問題是通過repository.Products的強類型視圖。如果我需要通過另一個實體,這是非常可行的,我將如何實現這一目標?

回答

2

你可以建立一個視圖模型看起來像下面這樣:

public class YourViewModel 
{ 
    public List<Product> Products { get; set; } 
    public List<OtherEntity> OtherEntities { get; set; } 
} 

然後你可以用資源庫中,包含了所有 你需要滿足您的要求和/或businesslogic方法的服務:

public class YourService 
{ 
    private IProductRepository repository; 

    public List<Product> GetAllProducts() 
    { 
     return this.repository.Products.ToList(); 
    } 

    public List<OtherEntity> GetAllOtherEntites() 
    { 
     return this.repository.OtherEntites.ToList(); 
    } 
} 

終於在控制器您填寫適當的視圖模型

public class ProductController : Controller 
{ 
    private YourControllerService service = new YourControllerService(); 
    // you can make also an IService interface like you did with 
    // the repository 

    public ProductController(YourControllerService yourService) 
    { 
     service = yourService; 
    } 

    public ViewResult List() 
    { 
     var viewModel = new YourViewModel(); 
     viewModel.Products = service.GetAllProducts(); 
     viewModel.OtherEntities = service.GetAllOtherEntities(); 

     return View(viewModel); 
    } 
} 

現在,您在ViewModel上有多個實體。

+1

能否請你加你將如何再在視圖中使用這個? – Zapnologica 2013-07-15 20:28:37

+0

你的服務是什麼?應該在哪裏添加? – Icet 2015-09-11 10:28:22

0

也許它不是直接回答你的問題,但它是連接的。

如果你正確地傳遞模型查看,你可以處理像這樣

@model SolutionName.WebUI.Models.YourViewModel 

@Model.Product[index].ProductId 
@Model.OtherEntity[index].OtherId 

我知道這是舊的文章,但它有可能幫助別人:)

相關問題