zoukankan      html  css  js  c++  java
  • ASP.NET MVC中ViewData、ViewBag和TempData

    1.ViewData

    1.1 ViewData继承了IDictionary<string, object>,因此在设置ViewData属性时,传入key必须要字符串型别,value可以是任意类型。

    1.2 ViewData它只会存在这次的HTTP要求而已,而不像Session可以将数据带到下HTTP要求。

        public class TestController : Controller
        {
            public ActionResult Index()
            {
                ViewData["msg"] = "123123";
                return View();
            }
        }
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>页面</h2>
    <h2>@ViewData["msg"]</h2>

    2.ViewData的扩张属性ViewData.Model

        public class TestController : Controller
        {
            public ActionResult Index()
            {
                User aa = new User() { Age = 1, Name = "linq" };
                //ViewData.Model = aa;
                return View(aa);
            }
        }
    @{
        ViewBag.Title = "Index";
    }
    @model MvcApplication1.Models.User
    <h2>页面</h2>
    <h2>@Model.Age</h2>
    <h2>@Model.Name</h2>

    3.ViewBag

    3.1 严格来说ViewBag和ViewData的区别就是ViewBag是dynamic动态型别

        public class TestController : Controller
        {
            public ActionResult Index()
            {
                User aa = new User() { Age = 1, Name = "linq" };
                ViewBag.User = aa;
                return View();
            }
        }
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>页面</h2>
    <h2>@ViewBag.User.Age</h2>
    <h2>@ViewBag.User.Name</h2>

    4.TempData

    4.1 TempData的信息在"一次网页要求内有效"(ActionResult的返回类型必须为RedirectToRouteResult或RedirectToRouteResult类别,除此以外只要有取用的TempData的键值,默认就会在当次网页就要求清除,但你只是单纯设置了TempData的值,并没有读取行为的话,TempData还是会保留到下次使用)

        public class TestController : Controller
        {
            public ActionResult Index(string msg)
            {
                TempData["msg"] = msg;
                return RedirectToAction("Index2");
            }
    
            public ActionResult Index2()
            {
                return View();
            }
        }
  • 相关阅读:
    数据库与数据仓库的比较Hbase——Hive
    log4j 配置使用
    hadoop Datanode Uuid unassigned
    kafka相关文章引用
    kafka可靠性
    kafka基本原理
    html
    并发编程
    Python之系统交互(subprocess)
    网络编程
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/5484185.html
Copyright © 2011-2022 走看看