控制器通过ViewData查看

问题描述 投票:0回答:2

这是查看文件此处显示列表中学生的错误

@model IEnumerable<Controller2View.Models.Students>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div class="container">
    <div class="btn btn-default">
       <ul class="list-group">
    @foreach (var std in ViewData["StudentData"] as List<Students>)
    {
        <li class="list-unstyled">
            std.StudentName
        </li>
    }

</ul>
</div>

</div>
</body>
</html>

这是一个控制器文件,它有一个列表和viewdata,用于将数据从控制器传输到View。模型也很好地定义但不知道它不起作用。

public ActionResult Index()
    {
    List<Students> studentList = new List<Students>() {
                new Students(){ StudentId=1, StudentName="Steve"},
                new Students(){ StudentId=2, StudentName="Bill"},
                new Students(){ StudentId=3, StudentName="Ram"}
            };
        ViewData["StudentData"] = studentList;
        return View(studentList);
    }
asp.net-mvc
2个回答
0
投票

很高兴知道究竟什么不起作用。但还有两件事:

  1. 使用模型或ViewData的视图。
  2. 我想你得到一个包含“std.StudentName”的3个项目的列表,那是因为它必须读取@std.StudentName

0
投票

在控制器中使用以下代码

public ActionResult Index()
    {
    var studentList = new List<Students>() {
                new Students(){ StudentId=1, StudentName="Steve"},
                new Students(){ StudentId=2, StudentName="Bill"},
                new Students(){ StudentId=3, StudentName="Ram"}
            };

        return View(studentList);
    }

现在,在View中使用下面的代码

@model IEnumerable<Controller2View.Models.Students>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div class="container">
    <div class="btn btn-default">
       <ul class="list-group">
        @foreach (var std in Model)       
        {
        <li class="list-unstyled">
            std.StudentName
        </li>
        }    
       </ul>
    </div>    
</div>
</body>
</html>

希望它能工作,因为我直接使用模型而不是将其转换为列表。

© www.soinside.com 2019 - 2024. All rights reserved.