简体   繁体   English

ASP.NET MVC 5在View中获取继承的类数据

[英]ASP.NET MVC 5 Get inherited class data in View

I'm learning asp.net MVC and I'm trying to build an application but i can't have data displayed in my view. 我正在学习asp.net MVC,正在尝试构建应用程序,但是我的视图中无法显示数据。 I've search here but wasn't able to find an answer to this issue. 我在这里搜索,但找不到该问题的答案。 I have a model structure with Person which is my base class and two other classes that inherited from Person - Professor and Student. 我有一个基于Person的模型结构,这是我的基类,另外两个继承自Person的类是Professor和Student。 What i want is when i click the Students tab in my application it displays only students data and when i click Professors it displays only professors data with their common data and specific for each type. 我想要的是,当我单击应用程序中的“学生”选项卡时,它仅显示学生数据,而当我单击“教授”时,它仅显示具有共同数据且针对每种类型的教授数据。 Right now i have only one table "Person" with students and professors attributes. 现在,我只有一张表“ Person”,其中包含学生和教授的属性。 Thanks in advance!! 提前致谢!!

Here is my base class Person and subclasses Professor and Student 这是我的基类人和子类教授和学生

public abstract class Person
{
    public virtual int PersonID { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Email { get; set; }
    public virtual string Login { get; set; }
    public virtual string Senha { get; set; }
    public virtual string Address { get; set; } 
}
public class Professor : Person
{
    public string CREF { get; set; }
    public string Education { get; set; }
    public virtual ICollection<Session> Sessions { get; set; }
} 
public class Student : Person
{
    public DateTime SessionStart { get; set; }
    public DateTime SessionEnd { get; set; }
    public virtual ICollection<TSession> Sessions { get; set; }
}

and here is my StudentController 这是我的StudentController

public class StudentController : Controller
{
    private SessionContext db = new SessionContext();

    public ActionResult Index()
    {
        return View(db.People.ToList());
    }
}

Here is my Index studentView 这是我的索引studentView

....

<table class="table">
    <tr>
        <th>@Html.DisplayNameFor(model => model.FirstName)</th>
        <th>@Html.DisplayNameFor(model => model.LastName)</th>
         ....
    </tr>
    @foreach (var item in Model) {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
            <td>@Html.DisplayFor(modelItem => item.LastName)</td>
            ....
        </tr>
    }
</table>

I have saved my original answer in a gist as it didn't really answer the OP's question. 我将原始答案保存在要点中,因为它并未真正回答OP的问题。 Ironically the source I was using was designed to solve the opposite problem, where two tables needed to be combined into a single page. 具有讽刺意味的是,我正在使用的源旨在解决相反的问题,在该问题中,需要将两个表合并为一个页面。

Here the OP is saying that there is a database table Persons from which we'd like to extrapolate two Views, Professor and Student , and display them on different pages. OP在这里说有一个数据库表Persons,我们希望从数据库表中推断出ProfessorStudent两个视图,并将它们显示在不同的页面上。

Such that-- 这样-

//StudentController.cs
public class StudentController : Controller
{
    private SessionContext db = new SessionContext();

    public ActionResult Index()
    {
        var result = db.People.Where(x => !string.IsNullOrEmpty(x.Education));
        return View(result.ToList());
    }
}

and... 和...

//ProfessorController.cs
//...
    var result = db.People.Where(x => string.IsNullOrEmpty(x.Education));
//...

...could be one way of separating the views. ...可能是分离视图的一种方式。

However, as suggested in comments, if your design requires these objects to be displayed and treated separately in the application, you may just want to have multiple tables. 但是,正如注释中建议的那样,如果您的设计要求这些对象在应用程序中显示和单独处理,则您可能只想拥有多个表。 One example in TSQL: TSQL中的一个示例:

CREATE TABLE dbo.Person (
    Id int NOT NULL PRIMARY KEY,
    Name nvarchar(200) NOT NULL --unicode
);
CREATE TABLE dbo.Professor (
    Id int NOT NULL PRIMARY KEY,
    Education nvarchar(50) NOT NULL,
    PersonId int FOREIGN KEY REFERENCES Person.Id
);
--etc

But since I'm not a DBA and you're using ASP.NET you can use Entity Framework's Code First table generation, which I think is what you're hinting at above: 但是由于我不是DBA,而且您正在使用ASP.NET,因此可以使用Entity Framework的Code First表生成,我想这就是您上面暗示的内容:

public class Person
{
    public int PersonId { get; set; }
    [Required] // == NOT NULL
    public string Name { get; set; }
    // demais... (the rest)
}

public class Professor // no inheritance!
{
    public int ProfessorId { get; set; }
    [Required]
    public string Education { get; set; }
    [ForeignKey("PersonId")]
    public Person Person { get; set; }
}

Note that this is a 1-1 relationship, and honestly I haven't validated this. 请注意,这是1-1的关系,老实说,我尚未对此进行验证。 Julie Lerman has many posts on Microsoft's Data Developer Center website, such as this one that goes into these relationships. 朱莉·莱尔曼(Julie Lerman)在Microsoft的数据开发人员中心网站上有很多帖子,例如涉及这些关系的这篇文章 (That's my best Quick Googling (tm) and points to Entity Framework 4.1, so I'm sure you can find something newer. But the principles should still hold.) (这是我最好的Quick Googling(tm),它指向Entity Framework 4.1,所以我确定您可以找到较新的东西。但是原则仍然适用。)

Whew! 呼!

谢谢所有花时间尝试帮助我解决此问题的人,我能够从继承的类中提取特定属性,并以不同的视图显示它,因此,我决定创建两个表Student和Professor,这解决了我的问题。

This question has 2 parts, namely, displaying data on a view and getting the data from a database via some method like Entity Framework . 这个问题分为两部分,即在视图上显示数据和通过诸如Entity Framework类的方法从数据库中获取数据。 And because this is an ASP.NET MVC question I am only going to answer the displaying of data on the view. 并且因为这是一个ASP.NET MVC问题,所以我只回答视图上数据的显示。 How you get your data back is up to you. 如何取回数据取决于您。

I personally would have 2 tables in the database for this, one for students and one for professors. 我个人将在数据库中有2个表,一个用于学生,一个用于教授。 This is debatable but this is how I would do it. 这值得商but,但这就是我的做法。

You professor and student classes look correct to me. 您的professor班和student班对我来说似乎正确。

You will need to create a view model for this. 您将需要为此创建一个视图模型。 View models contain data that you pass to the view. 视图模型包含您传递给视图的数据。 I gave a detailed answer on what view models are. 我对什么是视图模型给出了详细的答案。 Please read it: 请阅读:

What is ViewModel in MVC? 什么是MVC中的ViewModel?

First go and create your view model that you will send to the view. 首先,创建要发送到视图的视图模型。 You will probably display other data on the screen, but I am only going to display a list of students and a list of professors. 您可能会在屏幕上显示其他数据,但是我只显示学生列表和教授列表。 So for each you will have a property to contain the data: 因此,对于每个人,您将拥有一个包含数据的属性:

public class ViewModel
{
     public List<Student> Students { get; set; }

     public List<Professor> Professors { get; set; }
}

In your Index action method you will create an instance of this view model, populate it with student and professor data and then send it through to the view: 在您的Index action方法中,您将创建此视图模型的实例,用学生和教授数据填充它,然后将其发送到视图:

public ActionResult Index()
{
     // Please make use of a repository to handle this
     // You need to set up your data layer to handle students and professors
     SessionContext db = new SessionContext();

     ViewModel model = new ViewModel();

     // Get all the students
     model.Students = db.Students.ToList();
     // Get all the professors
     model.Professors = db.Professors.ToList()

     return View(model);
}

Now you have your view model populated with student and professor data. 现在,您的视图模型已填充了学生和教授的数据。 You send it through to the view and the view will display it. 您将其发送到视图,视图将显示它。 You will need 2 HTML tables and have your tabs display the correct table when needed: 您将需要2个HTML表,并在需要时让标签页显示正确的表:

@model Project.Models.ViewModel

<table>
     @foreach (var student in Model.Students)
     {
          <tr>
               <td>@student.FirstName</td>
               <td>@student.FirstName</td>
          </tr>
     }
</table>

<table>
     @foreach (var professor in Model.Professors)
     {
          <tr>
               <td>@professor.FirstName</td>
               <td>@professor.FirstName</td>
          </tr>
     }
</table>

This is a simplistic approach and might not be what you are looking for but it will guide you on the correct path and give you ideas of what can be done. 这是一种简单的方法,可能不是您想要的方法,但是它将指导您正确的道路,并为您提供可以做什么的想法。

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

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