【问题标题】:How to Multiple models in one view [closed]如何在一个视图中使用多个模型[关闭]
【发布时间】:2015-07-16 08:55:31
【问题描述】:
public class Student
    {
      public string Name;
      public int Age;
    }

 List<Student> StudentList = new List<Student>
 {
   new Student{ Name = "Handri", Age = 8 },
   new Student{Name = "Jon Galloway", Age = 10},
   new Student{ Name = "Scott Hanselman", Age = 9}
 };

public class Teacher
  {
  public string Name;
  public int Age;
  }

 List<Teacher> TeacherList = new List<TeacherList>
 {
   new TeacherList { Name = "Jhon", Age = 30 },
   new TeacherList {Name = "JANE", Age = 25},
   new TeacherList { Name = "Peter", Age = 27}
 };

我的模型需要多个视图;

.................................................. ..................................................... ..................................................... .......

【问题讨论】:

  • 不要使用“动态”,这是一个流行词。准确解释您要做什么。您在寻找foreach() 循环吗?你的意思是Student 在你的代码中有Blog 吗?
  • 我使用@model 动态&lt;tbody&gt; @foreach (var item in Model) { &lt;tr&gt; &lt;td&gt; @Html.DisplayFor(m=&gt; item.Name)
  • 那么你的问题是什么?
  • 我需要在模型@Html.DisplayNameFor(m =&gt; model.name)的网格中添加标题
  • 您的列表中有 2 种数据类型吗?

标签: c# asp.net-mvc razor


【解决方案1】:

使用元组

元组对象是不可变的、固定大小的有序序列对象。它是一种具有特定数量和元素序列的数据结构。 .NET 框架支持最多七个元素的元组。

使用这个元组对象,我们可以将多个模型从控制器传递到视图。

控制器代码

public ActionResult IndexTuple()
{
    ViewBag.Message = "Welcome to my demo!";
    var tupleModel = new Tuple<List<Teacher>, List<Student>>(GetTeachers(), GetStudents());
    return View(tupleModel);
}

View Code

@using MultipleModelInOneView;
@model Tuple <List<Teacher>, List <Student>>
@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2> 
<p><b>Teacher List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
    </tr>
    @foreach (Teacher teacher in Model.Item1)
    {
        <tr>
            <td>@teacher.TeacherId</td>
            <td>@teacher.Code</td>
            <td>@teacher.Name</td>
        </tr>
    }
</table>
<p><b>Student List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (Student student in Model.Item2)
    {
        <tr>
            <td>@student.StudentId</td>
            <td>@student.Code</td>
            <td>@student.Name</td>
            <td>@student.EnrollmentNo</td>
        </tr>
    }
</table>

更多详情请参考此链接 http://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2017-12-01
    • 2020-08-06
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多