将模型传递给Razor视图(局部视图等)

本文关键字:视图 局部 Razor 模型 | 更新日期: 2023-09-27 18:12:17

如何在c# MVC中传输部分/视图/控制器之间的数据/模型?

我试图复制这个例子,但是@model IEnumerable<MVC_BasicTutorials.Models.Student>给了我一个错误,在Model

下面有红线

_StudentList Partial.cshtml

@model IEnumerable<MVC_BasicTutorials.Models.Student>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.StudentName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Age)
    </th>
    <th></th>
</tr>
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.StudentName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Age)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.StudentId }) |
        @Html.ActionLink("Details", "Details", new { id=item.StudentId  }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.StudentId })
    </td>
</tr>
}
</table>

StudentController:

public class StudentController : Controller
{
 public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public int Age { get; set; }
    }
IList<Student> students;
public StudentController()
{
    students = new List<Student>{ 
                    new Student() { StudentId = 1, StudentName = "John", Age = 18 } ,
                    new Student() { StudentId = 2, StudentName = "Steve",  Age = 21 } ,
                    new Student() { StudentId = 3, StudentName = "Bill",  Age = 25 } ,
                    new Student() { StudentId = 4, StudentName = "Ram" , Age = 20 } ,
                    new Student() { StudentId = 5, StudentName = "Ron" , Age = 31 } ,
                    new Student() { StudentId = 6, StudentName = "Chris",  Age = 17 } ,
                    new Student() { StudentId = 7, StudentName = "Rob",Age = 19  } ,
                };
}
// GET: Student
public ActionResult Index()
{
    return View(students);
}
}

Index.cshtml:

@model IEnumerable<MVC_BasicTutorials.Models.Student>
<h3>Student List</h3>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@{
Html.RenderPartial("_StudentList", Model);
}

我读到这个https://stackoverflow.com/a/11326470/2441637,但无法得到解决:(如果我运行应用程序,我得到一个错误在@foreach (var item in Model)NullReferenceException: Object reference not set to an instance of an object.

将模型传递给Razor视图(局部视图等)

您的Student类被定义为StudentController的子类。因此,当使用该类作为模型类型时,需要使用适当的名称空间/完全限定类名。

将第一行改为

@model IEnumerable<PutYourNameSpaceHere.StudentController.Student>

您需要将PutYourNameSpaceHere替换为StudentController类下的命名空间

Student类移动到一个新文件(甚至是已经存在的),但是在名称空间MVC_BasicTutorials.Models

namespace MVC_BasicTutorials.Models
{
    public class Student
    {
       public int StudentId { get; set; }
       public string StudentName { get; set; }
       public int Age { get; set; }
    }
}

这样做的时候,你需要确保在你的StudentController中有一个using语句,这样你就可以使用这个类

所以添加这个作为StudentController类的第一行

@using MVC_BasicTutorials.Models