学习笔记:将数据从Controller传递到View的三种方法

2019-06-20  本文已影响0人  Memoyu

方法有三种,如下:


用法如下
首先,我们在Controller对应的Action下获取数据model,然后赋值ViewData字典的键值。

       public IActionResult List()
        {
            List<Student> modelList = _studentRepository.GetAllStudents();
            // 使用ViewData将PageTitle和Student模型传递给View
            ViewData["PageTitle"] = "Student List";
            ViewData["Student"] = modelList;
            return View();
        }

然后在对应的View中引用数据模型@using Web.Models,并获取ViewData对应键的值Title@ViewData["PageTitle"] 和 model@{ var student = ViewData["Student"] as List<Student>; }

@using Web.Models
<html>
<head>
    <title></title>
</head>
<body>
    <h3>@ViewData["PageTitle"]</h3>
    @{ var student = ViewData["Student"] as List<Student>; }
<table>
    @{ foreach (var item in student)
        {
            <tr> <td>Id:</td>  <td>@item.Id</td> </tr>
            <tr> <td>名字:</td>  <td>@item.Name</td> </tr>
            <tr> <td>班级:</td>  <td>@item.ClassName</td> </tr>
            <tr> <td>邮箱:</td>  <td>@item.Email</td> </tr>
        }
    }
</table>
</body>
</html>
 public IActionResult List()
        {
            ////使用ViewBag传递model
            List<Student> modelList = _studentRepository.GetAllStudents();
            // 使用ViewBag将PageTitle和Student模型传递给View
            ViewBag.PageTitle = "Student List";
            ViewBag.StudentList = modelList;
            return View();


        }
@using Web.Models
<html>
<head>
    <title></title>
</head>
<body>
    <h3>@ViewBag.PageTitle</h3>
    @{ var student = ViewBag.StudentList as List<Student>; }
<table>
    @{ foreach (var item in student)
        {
            <tr> <td>Id:</td>  <td>@item.Id</td> </tr>
            <tr> <td>名字:</td>  <td>@item.Name</td> </tr>
            <tr> <td>班级:</td>  <td>@item.ClassName</td> </tr>
            <tr> <td>邮箱:</td>  <td>@item.Email</td> </tr>
        }
    }
</table>
</body>
</html>
        public IActionResult List()
        {
            List<Student> modelList = _studentRepository.GetAllStudents();
            // 使用ViewData将PageTitle和Student模型传递给View
            ViewBag.PageTitle = "Student List";
            //ViewBag.StudentList = modelList;
            return View(modelList);
        }

与以上两种方法的区别在于 创建强类型视图,使用@model指令在视图中指定模型类型,然后需要使用的时候使用@Model,这时,我们可以发现可以使用Model点出智能提示(源于我传入的数据为List,所以需要转化@model List<Web.Models.Student>)。

@model List<Web.Models.Student>
<html>
<head>
    <title></title>
</head>
<body>
    <h3>@ViewBag.PageTitle</h3>
    <table>
        @{ foreach (var item in Model)
            {
                <tr> <td>Id:</td>  <td>@item.Id</td> </tr>
                <tr> <td>名字:</td>  <td>@item.Name</td> </tr>
                <tr> <td>班级:</td>  <td>@item.ClassName</td> </tr>
                <tr> <td>邮箱:</td>  <td>@item.Email</td> </tr>
            }
        }
    </table>
</body>
</html>

学习笔记来源于:52abp学习文档

上一篇 下一篇

猜你喜欢

热点阅读