• 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();
            }
        }
  • 相关阅读:
    hdu--2578--与女孩约会
    hdu--2588--欧拉函数||容斥原理
    hdu--2586--lca_tarjan<证明tarjan这个人很流弊>
    hdu--3743--归并排序<自顶向下&&自底向上>2种写法
    hdu--4911--归并排序||树状数组
    hdu--2639--01背包第K解<不同决策的不同解法>
    hdu--2642--二维BIT
    hdu--3833--4000ms才能过的O(N^2)算法
    hdu--3835--最简单的数学..
    hdu--3836--tarjan+缩点
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/5484185.html
Copyright © 2020-2023  润新知