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();
            }
        }
  • 相关阅读:
    与答辩有关资料
    SpringBoot技术优点
    【知识库】-简单理解CrudRepository接口中的方法
    【知识库】-通俗理解OAuth2.0协议用于第三方登陆
    毕业设计介绍所用
    JavaWeb_(视频网站)_七、推荐模块1
    JavaWeb_(视频网站)_六、分页模块1
    JavaWeb_(视频网站)_五、视频模块2 辅助功能
    JavaWeb_(视频网站)_五、视频模块1 视频上传
    JavaWeb_(视频网站)_四、博客模块2
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/5484185.html
Copyright © 2011-2022 走看看