且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ASP.NET MVC 4中正确使用元组

更新时间:2023-02-15 22:15:27

本质上,您只是试图将多个模型传递给视图.由于您只能将一种类型传递给视图,因此执行所需操作的方法是将模型包装在视图模型中,然后将其传递给视图.像这样:

Essentially, you're just trying to pass multiple models to your view. As you can only pass one type to a view, the way to do what you want is to wrap your models in a view model and pass that to your view instead. Something like:

public class ProductViewModel
{
    public IPagedList<Product> Products { get; set; }
    public IEnumerable<Order> Orders { get; set; }
}

public ActionResult Index()
{
    var model = new ProductViewModel();
    model.Products = // ... fetch from database
    model.Orders = // ... fetch from database

    return View(model);
}

现在可以将视图强类型化为视图模型:

The view can now be strongly-typed to the view model:

@model ProductViewModel