Wednesday, 20 September 2017

MVC 4 how pass data correctly from controller to view

You should create a ViewModel with all of your data needed and then pass that down to the view.
public class ViewModel 
{
   public List<int> Melt1 { get; set; }

   public void LoadMeltProperties() 
   {

       if (Melt1 == null) 
       {
          Melt1 = new List<int>();
       }

       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
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Blog Archive