问题描述
我有一个带有多个视图的 MVC 4 应用程序.IE.产品、食谱、分销商和商店.
I have an MVC 4 application with several views. I.e. Products, Recipes, Distrubutors & Stores.
每个视图都基于一个模型.
Each view is based around a model.
让我们保持简单,说我所有的控制器都传递了一个类似的视图模型,看起来像我的 Product 操作:
Let's keep it simple and say that all my controllers pass a similar view-model that looks something like my Product action:
public ActionResult Index()
{
return View(db.Ingredients.ToList());
}
好的,这很好,没有问题.但是现在我的所有页面都正常工作了,我想更改导航(每个视图都有下拉菜单)以加载该模型中的项目.
Ok so this is fine, no problems. But now that all of my pages work I want to change my navigation (which has dropdowns for each view) to load the items in that model.
所以我会有一个带有 4 个按钮(产品、食谱、分销商和商店)的导航.
So I would have a navigation with 4 Buttons (Products, Recipes, Distrubutors & Stores).
当您滚动每个按钮(假设我们滚动产品按钮)时,下拉菜单会列出产品.
When you roll over each button (let's say we roll over the products button) then a dropdown would have the Products listed.
为此,我需要创建某种类型的 ViewModel,将所有 4 个模型组合在一起.显然我不能只为每个导航元素剪下一个 PartialView 并使用
To do this I need to create some type of ViewModel that has all 4 of those models combined. Obviously I can't just cut out a PartialView for each navigation element and use
@model IEnumerable<GranSabanaUS.Models.Products>
然后重复该下拉菜单的产品,因为那样导航将只在产品视图中起作用,而在其他任何地方都不起作用.
And repeat out the Products for that dropdown, because then that navigation would only work in the Product View and nowhere else.
(解后)
是的 ROWAN 您在我创建的导航类型中是正确的,请参见此处:
(After the solution)
AND YES ROWAN You are correct in the type of nav I am creating, see here:
推荐答案
public class MenuContents
{
public IEnumerable<Products> AllProducts { get; set; }
public IEnumerable<Recepies> AllRecepies { get; set; }
public IEnumerable<Distributors> AllDistributors { get; set; }
public IEnumerable<Stores> AllStores { get; set; }
private XXXDb db = new XXXUSDb();
public void PopulateModel()
{
AllProducts = db.Products.ToList();
AllRecepies = db.Recepies.ToList();
AllDistributors = db.Distributors.ToList();
AllStores = db.Stores.ToList();
}
}
然后在你的控制器中
public ActionResult PartialWhatever()
{
MenuContents model = new MenuContents();
model.PopulateModel();
return PartialView("PartialViewName", model);
}
然后在你的局部视图中
@Model MenuContents
... do whatever here
这篇关于为导航创建 ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!