将多个模型传递给使用MVC3和Ninject的视图
问题描述:
我是新来的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的强类型视图。如果我需要通过另一个实体,这是非常可行的,我将如何实现这一目标?
答
你可以建立一个视图模型看起来像下面这样:
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上有多个实体。
答
也许它不是直接回答你的问题,但它是连接的。
如果你正确地传递模型查看,你可以处理像这样
@model SolutionName.WebUI.Models.YourViewModel
@Model.Product[index].ProductId
@Model.OtherEntity[index].OtherId
我知道这是旧的文章,但它有可能帮助别人:)
能否请你加你将如何再在视图中使用这个? – Zapnologica 2013-07-15 20:28:37
你的服务是什么?应该在哪里添加? – Icet 2015-09-11 10:28:22