MVC 4 如何正确地将数据从控制器传递到视图 [英] MVC 4 how pass data correctly from controller to view

查看:32
本文介绍了MVC 4 如何正确地将数据从控制器传递到视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个带有 LINQ 语句的控制器,我正在将数据从它传递到我的视图.我试图找到一种更有效、更好的编码方法来做到这一点.我的家庭控制器声明如下.

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 home controller statement is as follows.

Var Melt
  Furnace1 =
           (from item in db.tbl_dppITHr
           where item.ProductionHour >= StartShift && item.ProductionHour <= EndDate
           select item).Sum(x => x.Furnace1Total),

ViewData["Furnace1Total"] = Melt.Furnace1;

在我看来,我然后引用 ViewData 来显示这一点.使用

In my view i then reference the ViewData To show this. Using

 @model dynamic

现在我在 Index 方法中有相当多的 linq 语句.对于每个我正在做的 ViewData[]

Now i have quite alot of linq statements inside the Index method. And for each one i am doing the ViewData[]

我希望有人可以展示我如何在没有 ViewData 或 ViewBag 方法的情况下将多个 var 从控制器传递到视图.在我看来,我将如何访问它.

I am hoping that someone can show how i pass more than one var from a controller across to a view without the ViewData or ViewBag methods. And how i would get access to this within my view.

推荐答案

您应该使用您需要的所有数据创建一个 ViewModel,然后将其传递给视图.

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);
}

然后在您的视图中,您可以使用 strong typed 模型而不是 dynamic

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

@model ViewModel

然后您可以通过以下方式遍历您的 ViewModel 属性:

You can then iterate over your ViewModel properties via:

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

这篇关于MVC 4 如何正确地将数据从控制器传递到视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆