简体   繁体   English

如何在局部视图中使用不同的 model ASP.NET Core MVC

[英]How to use a different model in partial view ASP.NET Core MVC

This is my first MVC project and I'm trying to understand how each component works with the other.这是我的第一个 MVC 项目,我试图了解每个组件如何与另一个组件一起工作。 I am building a basic school system (courses, students, and enrollments).我正在建立一个基本的学校系统(课程、学生和招生)。

In my main view ( Calculus.cshtml ), I am displaying the course name and description (working properly) from my CourseController .在我的主视图 ( Calculus.cshtml ) 中,我从我的CourseController显示课程名称和描述(正常工作)。 Now, I want to use a partial view ( _studentList ) to display a list of students that are enrolled in the course from a controller called StudentController .现在,我想使用部分视图 ( _studentList ) 显示从名为StudentController的 controller 注册的学生列表。

I tried a couple of different things:我尝试了几种不同的方法:

First I just used the function in my controller to pass the List<Student> to the partial view like so:首先,我只是在我的 controller 中使用 function 将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);
}

(I also want to mention my List is populating correctly, it's simply getting this list to the view so I can display the contents). (我还想提一下我的列表填充正确,它只是将此列表添加到视图中,以便我可以显示内容)。

Calculus.cshtml微积分.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 _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>

However, when I try this I get an error saying:但是,当我尝试这个时,我收到一条错误消息:

The model item passed into the dictionary is of type 'SchoolSystem.Models.Course', but this dictionary requires a model item of type 'SchoolSystem.Models.Student'传入字典的 model 项的类型为“SchoolSystem.Models.Course”,但该字典需要“SchoolSystem.Models.Student”类型的 model 项

I was then reading about view models and tried to make one but I still don't know how to use a different model in the partial view.然后我正在阅读有关视图模型并尝试制作一个,但我仍然不知道如何在局部视图中使用不同的 model。 Is that even possible?这甚至可能吗?

In my StudentList() function, I am returning a parameter to the partial view - how would I use that?在我的StudentList() function 中,我将一个参数返回到部分视图 - 我将如何使用它?

return PartialView("_StudentList", StudentList);

Student.cs Model Student.cs Model

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; }
    }
}

Sorry for all the questions, I'm just trying to understand how to get my program working right.抱歉所有问题,我只是想了解如何让我的程序正常工作。

For your partial view have a foreach loop,your partial view is expecting a model of type IEnumerable<Student> .And the easier way is to return view with course model and student model if they have relationships,no need to specify a method to return partial view.对于您的部分视图,您的部分视图是期望Z20F35E630DAF44DBFA4C3F68F68F539999999999999999999999999999D8CZ of IENUMSOUDE IEnumerable<Student> 。部分观点。

Here is a working demo:这是一个工作演示:

Model: Model:

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; }
}
public class Course
{
    public int ID { get; set; }
    public string CourseDescription { get; set; }
    public List<Student> Students { get; set; }
}

View(Calculus.cshtml):查看(Calculus.cshtml):

@model Course

<div>
    <h4>Calculus</h4>
    <hr />
    <dl class="row">
        <dt class="col-sm-5">
            @Html.DisplayNameFor(model => model.CourseDescription)
        </dt>
        <dd class="col-sm-5">
            @Html.DisplayFor(model => model.CourseDescription)
        </dd>
    </dl>
</div>

<dd class="col-sm-10">
    <partial name="_StudentList" model="Model.Students" />   //change here....

</dd>

Partial View:局部视图:

@model IEnumerable<Student>   //change here....

<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>

Controller: Controller:

//GET:Home/Calculus/5
public async Task<IActionResult> Calculus(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var model = await _context.Course.Include(s=>s.Students)
        .FirstOrDefaultAsync(m => m.ID == id);
    return View(model);
}

Result:结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM