【发布时间】:2017-02-16 21:59:27
【问题描述】:
如何在 C# MVC 中的部分/视图/控制器之间传输数据/模型?
我正在尝试复制 this 示例,但 @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.
【问题讨论】:
-
MVC_BasicTutorials.Models命名空间下是否有一个名为Student的类? -
根本没有
MVC_BasicTutorials.Models,不知道应该在哪里以及如何 -
因为学生类在你的学生控制器中..路径可能是
{SolutionName}.Controllers.StudentController.Student -
完整的 pah 不起作用,它只有在我使用
[myExistingNameSpace].Model创建了一个单独的类后才起作用,非常感谢您的反馈。
标签: c# asp.net-mvc razor partial-views