MVC 4如何从控制器正确地传递数据,查看 [英] MVC 4 how pass data correctly from controller to view

查看:180
本文介绍了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

现在我有相当的很多指数方法中的LINQ语句。而对于每一个我做的计算机[]

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

我希望有人可以告诉我如何传递多个变种从控制器向对面没有ViewData的或ViewBag方法的视图。我怎么会得到在我看来上网本。

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.

推荐答案

您应该创建一个视图模型所需的所有数据,然后传递到视图。

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

然后在您的视图中,您可以使用强类型模式,而不是动态

@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天全站免登陆