【发布时间】:2021-03-15 02:12:17
【问题描述】:
这是我的第一个 MVC 项目,我试图了解每个组件如何与另一个组件协同工作。我正在建立一个基本的学校系统(课程、学生和招生)。
在我的主视图 (Calculus.cshtml) 中,我正在显示来自我的CourseController 的课程名称和描述(正常工作)。现在,我想使用局部视图 (_studentList) 来显示从名为 StudentController 的控制器注册的学生列表。
我尝试了几种不同的方法:
首先我只是使用控制器中的函数将List<Student> 传递给局部视图,如下所示:
public async Task<IActionResult> StudentList(int id)
{
List<Student> StudentList = await _context.Student
.Include(s => s.Course)
.AsNoTracking()
.Where(x => x.Course.ID == id)
.ToListAsync();
return PartialView("_StudentList", StudentList);
}
(我还想提一下我的 List 填充正确,它只是将此列表添加到视图中,以便我可以显示内容)。
Calculus.cshtml
@model SchoolSystem.Models.Course
<div>
<h4>Calculus</h4>
<hr />
<dl class="row">
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.CourseDescription)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.CourseDescription)
</dd>
</dl>
</div>
<dd class="col-sm-10">
<partial name="_StudentList" />
</dd>
_StudentList.cshtml
@model SchoolSystem.Models.Student
<table class="table">
<tr>
<th>Student Name</th>
<th>StudentDOB</th>
<th>StudentPhoneNum</th>
<th>StudentPhoneNum</th>
</tr>
@foreach (var student in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => student.StudentName)
</td>
<td>
@Html.DisplayFor(modelItem => student.StudentDOB)
</td>
<td>
@Html.DisplayFor(modelItem => student.StudentPhoneNum)
</td>
<td>
@Html.DisplayFor(modelItem => student.studentAddress)
</td>
</tr>
}
</table>
但是,当我尝试这个时,我收到一条错误消息:
传入字典的模型项是“SchoolSystem.Models.Course”类型的,但是这个字典需要一个“SchoolSystem.Models.Student”类型的模型项
当时我正在阅读有关视图模型的信息并尝试制作一个,但我仍然不知道如何在局部视图中使用不同的模型。这可能吗?
在我的 StudentList() 函数中,我将一个参数返回到局部视图 - 我将如何使用它?
return PartialView("_StudentList", StudentList);
Student.cs 模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace SchoolSystem.Models
{
public class Student
{
public int ID { get; set; }
[Display(Name = "Student Name")]
public string StudentName { get; set; }
[Display(Name = "Student Date of Birth")]
public string StudentDOB { get; set; }
[Display(Name = "Student Phone Number")]
public string StudentPhoneNum { get; set; }
[Display(Name = "Student Address")]
public string studentAddress { get; set; }
public virtual Course Course { get; set; }
}
}
抱歉所有问题,我只是想了解如何让我的程序正常运行。
【问题讨论】:
-
如果你想从另一个主视图渲染局部视图,你需要将模型对象从主视图本身传递给视图。
<partial name="_StudentList" />会将主视图的模型对象传递给局部视图。而且它与局部视图模型类型不匹配,这就是您收到此错误的原因。 -
你的模型设计是什么?能分享给我们吗?
-
@ChetanRanpariya 我明白你在说什么,比如:@Html.Partial("_StudentList", myModel)?问题是,我的主要观点是使用不同的模型(Model.course),我需要model.student。那么如何将 model.student 传递给局部视图呢?
-
您需要使用
@Html.RenderAction("StudentList", Model.StudentId)这将调用控制器动作并返回部分视图。您还需要在_StudentList.cshtml中将模型类型更改为@model List<SchoolSystem.Models.Student> -
@rena 我添加了学生模型^
标签: c# asp.net model-view-controller view asp.net-core-mvc