• 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();
            }
        }
  • 相关阅读:
    ASM认证与口令文件
    asm 兼容性、asm 主要参数管理
    最常见的5个导致 RAC 实例崩溃的问题
    oracle隐含参数的查看与修改
    三种 Failover 之 Client-Side Connect time Failover、Client-Side TAF、Service-Side TAF
    Oracle RAC TAF 无缝failover
    oracle rac的特征
    安装ORACLE时在Linux上设置内核参数的含义
    关于GCC的理解——On the understanding of the GCC
    java中的闭包和回调
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/5484185.html
Copyright © 2020-2023  润新知