ViewBag、ViewData和TempData使用方法、区别与联系

一、区别与联系

  ViewData 和 TempData 都可以传递弱类型数据,区别如下:TempData 只在当前 Action 中有效,生命周期和 View 相同;保存在Session中,Controller每次执行请求的时候,会从Session中先获取TempData,而后清除Session,获取完TempData数据,虽然保存在内部字典对象中,但是其集合中的每个条目访问一次后就从字典表中删除。因此TempData 的数据至多只能经过一次Controller传递,并且每个元素至多只能被访问一次,访问以后,自动被删除。

  ViewData与ViewBag使用的是同一个数据源,因此数据一样,只是ViewBag 不再是字典的键值对结构,而是 dynamic 动态类型(http://www.cnblogs.com/kissdodog/archive/2013/01/20/2868644.html),它会在程序运行的时候动态解析。但是只有当访问的关键字是一个有效的C#标识符时,ViewBag才起作用。例如ViewData["have space"]用ViewBag是无法访问的。ViewData[]传递的key/value,value是Object数据类型,传递到View层之后要用as运算转换一下才能够变为强类型数据,但是ViewBag是在运行时才确定数据类型,因此根本不用转换。此处的不用转换类型是所有的类型,例如能够随意传递DateTime,String,其他自定义类型等等。但是就效率而言,ViewData[]稍高。

  例如:

        public ActionResult Index()
        {
            ViewData["Name"] = "李四";
            ViewBag.Name = "张三";
            return View();
        }
  @ViewData["Name"];  //输出张三
  @ViewBag.Name;     //输出张三

二、使用ViewData或ViewBag传递强类型数据

  Controller代码:

复制代码
        public ActionResult Index()
        {
            var PeopleList = new List<People_Model>();
            for (int i = 0; i < 10; i++)
            {
                People_Model p = new People_Model();
                p.Id = i;
                p.Name = "我是" + i;
                p.Age = 20 + i;
                PeopleList.Add(p);
            }
            ViewData["list"] = PeopleList;
            return View();
        }
复制代码
    public class People_Model
    {
        public int Id { get; set; }
     public string Name { get; set; }
     public int Age { get; set; }
    }
复制代码
<table>
    <tr>
        <td>编号</td>
        <td>姓名</td>
        <td>年龄</td>
    </tr>
@foreach(People_Model item in (ViewData["list"] as IEnumerable<People_Model>))
{ 
    <tr>
        <td>@item.Id</td>
        <td>@item.Name</td>
        <td>@item.Age</td>
    </tr>
}
</table>
复制代码

   以上代码再来改写一下,以说明ViewData与ViewBag的区别,ViewBag是个好东西。先放入一个公共类代码:

复制代码
    public class Person
    {
        public Person(int id, int age, string name)
        {
            this.Id = id;
            this.Age = age;
            this.Name = name;
        }

        public int Id { get; set; }
     public int Age { get; set; }
     public string Name { get; set; }
    }
复制代码

  控制器代码:  由于ViewBag与ViewData使用的是同一个数据源,因此控制器就使用ViewData传递数据,但是在视图里用不同的东西获取。

复制代码
         public ActionResult Index()
        {
            Person p1 = new Person(1, 20, "张飞");
            Person p2 = new Person(2, 21, "关羽");
            Person p3 = new Person(3, 22, "刘备");
            List<Person> PersonList = new List<Person>();
            PersonList.Add(p1);
            PersonList.Add(p2);
            PersonList.Add(p3);
            ViewData["PList"] = PersonList;
            return View();
        }
复制代码

  视图代码:

复制代码
@foreach (var p in ViewBag.PList)    //应该注意到此行代码,根本不用转换数据类型
{
    <div style=" line-height: 1.5 !important;">>@p.Name;</div>
}

@foreach (var p in ViewData["PList"] as List<MVC_AjaxTest.Controllers.Person>)  //而用ViewData读取的话要用as运算符转换为强类型数据
{
    <div style=" line-height: 1.5 !important;">>@p.Name;</div>
}
复制代码

三、TempData使用

  下面用TempData来实现一个当提交表单时弹出提示,非表单提交不弹出提示的示例:

  Controller:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string name)
        {
            TempData["Tips"] = "表单提交成功!";
            return View();
        }
    }
}
复制代码

  视图:

复制代码
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Index</title>
    <script src="/Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            <% if(TempData["Tips"] != null) %> 
            <% { %>
                    alert('<%= TempData["Tips"]%>');
            <% } %>
        })
    </script>
    
</head>
<body>
    <div>
        <form action="/Home/Index" method="post">
            <input type="text" name="name" value="测试js" />
            <input type="submit" />
        </form>
    </div>
</body>
</html>
复制代码

  不知道大家是否有遇到过,提交了表单之后,老是不知道如何获取提交成功的提示。实际上,一个普通的表单提交,还真的比较适合页面提交。如果你出于其他原因觉得不适合使用AJAX的情况下,使用TempData的方式适合于不需要跳转的情况,提交后直接可以在本页面继续操作的情况。

  TempData内部是将数据保存在Session里面的,至于实现了哪些接口,不说,因为知道了也没办法实现自定义的TempData。

posted on 2015-01-05 15:17  铭轩同学 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/mingxuantongxue/p/4203681.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值