MVC 4 how pass data correctly from controller to view

前端 未结 4 1316
长发绾君心
长发绾君心 2020-11-29 08:30

I currently have a controller with a LINQ statement that i am passing data from to my view. I am trying to find a more efficient and better coding method to do this. My hom

4条回答
  •  抹茶落季
    2020-11-29 09:20

    You should create a ViewModel with all of your data needed and then pass that down to the view.

    public class ViewModel 
    {
       public List Melt1 { get; set; }
    
       public void LoadMeltProperties() 
       {
    
           if (Melt1 == null) 
           {
              Melt1 = new List();
           }
    
           Melt1 = (from item in db.tbl_dppITHr
           where item.ProductionHour >= StartShift && item.ProductionHour <= EndDate
           select item).Sum(x => x.Furnace1Total).ToList();
       }
    
       public ViewModel Load()
       {
           LoadMeltProperties();
           return this;
       }
    }
    
    public ActionResult YourControllerAction() 
    {
          var vm = new ViewModel().Load();
          return View("ViewName", vm);
    }
    

    Then in your View you can use a strongly typed model rather than dynamic

    @model ViewModel
    

    You can then iterate over your ViewModel properties via:

    foreach(var melt in Model.Melt1) {
         // do what you require
    }
    

提交回复
热议问题