MVC中的ViewData、ViewBag和TempData

一、ViewBag和ViewData的定义

 

public dynamic ViewBag { get; }  
public ViewDataDictionary ViewData { get; set; }  
public dynamic ViewBag { get; }
public ViewDataDictionary ViewData { get; set; }

 

二、ViewBag和ViewData的区别

 

viewdata viewbag
它是key/value字典集合 它是dynamic类型对象
从asp.net mvc1就有了 从asp.netmvc3才有
基于asp.netframework 3.5 基于asp.net framework4.0
viewdata比viewbag快 viewbag比viewdata慢
页面查询数据时需要转换合适的类型 在页面查询数据时不需要转换合适的类型
有一些类型转换代码 可读性较好

 

ViewBag不再是字典的键值对结构,而是dynamic动态类型,它会在程序运行的时候动态解析。

 1       ViewBag.NumberObjs = new string[] { "one", "two", "three" };  
 2           ViewData["NumberArrs"] = new string[] { "one", "two", "three" };  
 3  
 4           //正确,dynamic类型的解析作用,foreach可以使用  
 5           foreach (var item in ViewBag.NumberObjs)  
 6            {  
 7  
 8             }    
 9             //错误:foreach语句不可作用于object类型对象上  
10            foreach (var item in ViewData["NumberArrs"])  
11             {  
12  
13             }  

  

1、ViewBag其实本质就是ViewData,只是多了层Dynamic控制。所以,使用何种方式完全取决于你的个人爱好。

2、ViewBag和ViewData仅针对当前Action中有效,生命周期和view相同。

三、TempData

      保存在session中,Controller每次执行请求时,会从session中获取tempdata,而后清空session,获取完tempdata数据,虽然保存在内部字典中。但是字典中每个条目访问一次后就从字典中删除。因此Tempdata数据最多只能经过一次controller传递,并且每个元素最多只能访问一次,之后删除。

 

四、举例

在Controller中使用ViewData:

<pre name="code" class="csharp">public ActionResult UsingViewData()
        {
            ViewData["Title"] = "Using ViewData";
            ViewData["ProjectName"] = "My Test Project";
            ViewData["ProjectDescription"] = "This is TestProject to demo Viewdata and viewbag details";
            ViewData["StartDate"] = new DateTime(2011, 1, 1);
            ViewData["TotalPrice"] = 1000;
            ViewData["TotalDays"] = 100;
            Dictionary<string, string> stackholder = new Dictionary<string, string>();
            stackholder.Add("Client", "Mr.Client");
            stackholder.Add("Manager","Mr.Joy");
            stackholder.Add("Team Leader","Mr.Toy");
            stackholder.Add("Sr.developer","Mr.dojoy");
            stackholder.Add("developer","Mr.nodoy");
            ViewData["stackholder"]=stackholder;

            List<string>modules =new List<string>();
            modules.Add("Admin module");
            modules.Add("ShoppingCart module");
            modules.Add("CMS module");
            ViewData["modules"]=modules;
            return View();
        }
<div><span style="color: rgb(35, 35, 35); font-family: Verdana, Arial, helvetica, sans-seriff; font-size: 14px; line-height: 25px; orphans: 2; text-align: -webkit-auto; widows: 2;">对应UsingViewData View的cshtml:</span></div><pre name="code" class="html">@{
    ViewBag.Title = "UsingViewData";
}

<h1>@ViewData["Title"]</h1>
 <div>
   <div>
    <h2>Project Name : @ViewData["ProjectName"]</h2>
   </div>
   <div>
     ProjectDescription :   
     <p>"@ViewData["ProjectDescription"]".</p>
   </div>
   <div>
      Stack Holder :
      <br />

      <ul id="stakholder">
      @foreach ( var stakerholder in ViewData["stackholder"] as Dictionary<string, string> )
      {          
    <li>
        @stakerholder.Key   : @stakerholder.Value
    </li>
      }
     </ul>
   </div>
   <div>
     Project Details:<br />
     <div>
       module List  :
       <ul id="modulelist">
      @foreach ( var module in ViewData["modules"] as List<string> )
      {          
    <li>
        @module
    </li>
      }
     </ul>
        
     </div>
     Project StartDate : @ViewData["StartDate"]  <br />
     Project TotalPrice: @ViewData["TotalPrice"] <br />
     Project TotaDays  : @ViewData["TotalDays"] 
   </div>
 </div>

ViewBag controller:

        public ActionResult UsingViewBag()
        {
            ViewBag.Title = "Using ViewBag";
            ViewBag.ProjectName = "My Test Project";
            ViewBag.ProjectDescription = "This is Test Project to demo Viewdata and viewbag details";
            ViewBag.StartDate = new DateTime(2011, 1, 1);
            ViewBag.TotalPrice = 1000;
            ViewBag.TotalDays = 100;
            Dictionary<string, string> stackholder = new Dictionary<string, string>();
            stackholder.Add("Client", "Mr.Client");
            stackholder.Add("Manager", "Mr.Joy");
            stackholder.Add("Team Leader", "Mr.Toy");
            stackholder.Add("Sr.developer", "Mr.doyjoy");
            stackholder.Add("developer", "Mr.nodoy");
            ViewBag.stackholder = stackholder;

            List<string> modules = new List<string>();
            modules.Add("Admin module");
            modules.Add("ShoppingCart module");
            modules.Add("CMS module");
            ViewBag.modules = modules;
            return View();
        }

对应的页面:

@{
    ViewBag.Title = "UsingViewBag";
}

<h1>@ViewBag.Title</h1>
 <div>
   <div>
    <h2>Project Name : @ViewBag.ProjectName</h2>
   </div>
   <div>
     ProjectDescription :   
     <p>"@ViewBag.ProjectDescription.</p>
   </div>
   <div>
      Stack Holder :
      <br />

      <ul id="stakholder">
      @foreach ( var stakerholder in ViewBag.stackholder )
      {          
    <li>
        @stakerholder.Key   : @stakerholder.Value
    </li>
      }
     </ul>
   </div>
   <div>
     Project Details:<br />
     <div>
       module List  :
       <ul id="modulelist">
      @foreach ( var module in ViewBag.modules )
      {          
    <li>
        @module
    </li>
      }
     </ul>
        
     </div>
     Project StartDate : @ViewBag.StartDate.ToString("dd-MMM-yyyy") <br />
     Project TotalPrice: @ViewBag.TotalPrice  ₹  <br />
     Project TotaDays  : @ViewBag.TotalDays 
   </div>
 </div>

五、总结

1、ViewData和TempData是字典类型,赋值方式用字典方式,ViewData["myName"] 

2、ViewBag是动态类型,使用时直接添加属性赋值即可 ViewBag.myName

3、ViewBag和ViewData只在当前Action中有效,等同于View

4、TempData可以通过转向继续使用,因为它的值保存在Session中。但TempData只能经过一次传递,之后会被系统自动清除

5、ViewData和ViewBag中的值可以互相访问,因为ViewBag的实现中包含了ViewData

 

posted @ 2018-03-19 10:32  代码驿站  阅读(5333)  评论(0编辑  收藏  举报