• Mvc学习笔记(3)


    控制器将处理后的数据“传”给视图的方式

    public ActionResult Test()
            {
                List<Student> stuList = new List<Student>() 
                {
                  new Student(){ Age=20, Gender=true, Name="张三1"},
                  new Student(){ Age=21, Gender=true, Name="张三2"},
                  new Student(){ Age=22, Gender=true, Name="张三3"},
                  new Student(){ Age=23, Gender=true, Name="张三4"},
                  new Student(){ Age=24, Gender=true, Name="张三5"},
                };
    
                ViewData["stuName"] = "张三";
                ViewBag.stuAge = 22;            
                TempData["stuGender"] = "";
                return View(stuList);
            }

    <div> <!--ViewData--> @ViewData["stuName"] //张三 <br /> <!--ViewBag--> @ViewBag.stuName //张三 <br /> <!--ViewBag--> @ViewBag.stuAge //22 <br /> <!--ViewData--> @ViewData["stuAge"] //22 <br/> <!--Model--> @foreach (var item in Model as List<MVCTest001.Student>) { @item.Name<br/>     //张三1 张三2  张三3  张三4  张三5   } <br/> <!--TempData--> @TempData["stuGender"] //男 </div>

    @Html.Action(GetTempData)

    1.ViewData、ViewBag、TempData、Model

    如上图所示,我们用ViewData设置数据还是获取数据必须使用   ViewData[“stuName”] 说明ViewData是 ViewDataDictionary类型,简而言之ViewData就是一个键值对

    我们又从上图的输出结果看到ViewData和ViewBag输出的数据是相等的,那么从这一点我们可以看出ViewData和ViewBag的数据是共享的。那么下面我们通过反编译工具去看看他们是如何共享的

    那么我们打开Refletor.exe,搜索Controller(注意:这里你应该给反编译工具添加System.Web.Mvc.dll,系统默认没有),因为Controller类里的代码过多,我就不一一展示,但是我们在Controller类里没有发现ViewData还有ViewBag,那么我们就去父类里ControllerBase找,发现找到了;

    2015-04-05_085921

    我们点开ViewBag可以看到:

    2015-04-05_090421

    我们从this._dynamicViewDataDictionary=new DynamicViewDataDictionary(viewDataThunk);可以看出ViewBag就是从ViewData里面那的的数据,所以ViewBag和ViewData的数据是共享的。

    其中:ViewData和ViewBag本质上都是【ViewDataDictionary】类型,并且两者之间的数据是共享,只不过提供了不同的语法操作方式而已。

    1

    我们还有一种传输数据的方式就是View(stuList),如上图所示:你的stuList数据会赋值给model,然而ViewData.Model=model,所以ViewData的数据来自于ViewData.Model

    TempData也是通过键值对的形式进行传值,但是他的类型TempDataDictionary,他与ViewData和ViewBag不同点是在服务端跨Action传值,例如:

    public ActionResult GetTempData()
            {
                string msg=TempData["stuGender"].ToString();
                ViewBag.msg = msg;
                return View();
            }
    
    //视图代码:
     <div>
            <pre>
            @ViewBag.msg
            </pre>
        </div>

    这样我们就可以从Test控制器的 TempData[“stuGender”]获得数据:

    下面是一张请求的流程图:

    03在视图中请求Action-TempData

  • 相关阅读:
    mac下copy paste
    【leetcode】151. 颠倒字符串中的单词
    【leetcode】42. 接雨水
    【leetcode】239. 滑动窗口最大值
    【leetcode】 15. 三数之和
    【leetcode】18. 四数之和
    go env设置环境变量不起作用
    WSL2的迁移、默认设置、ssh、固定IP
    Shell的环境变量
    MOS, CMOS, 双向开关, PAD
  • 原文地址:https://www.cnblogs.com/changfutao/p/4393743.html
Copyright © 2020-2023  润新知