Create ViewModel for Navigation

前端 未结 2 647
太阳男子
太阳男子 2021-01-03 09:50

I have an MVC 4 application with several views. I.e. Products, Recipes, Distrubutors & Stores.

Each view is based around a model.

Let\'s keep it simple

2条回答
  •  被撕碎了的回忆
    2021-01-03 10:35

    public class MenuContents
    {
        public IEnumerable AllProducts { get; set; }
        public IEnumerable AllRecepies { get; set; }
        public IEnumerable AllDistributors { get; set; }
        public IEnumerable 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();
        }
    }
    

    Then in your controller

    public ActionResult PartialWhatever()
    {
        MenuContents model = new MenuContents();
        model.PopulateModel();
    
        return PartialView("PartialViewName", model);
    }
    

    Then in your partial view

    @Model MenuContents
    
    ... do whatever here
    

提交回复
热议问题