简体   繁体   English

通过ASP.NET MVC中的参数化构造函数访问其他类的属性

[英]Accessing other class's properties through paremeterized constructors in ASP.NET MVC

I'm working to generate HTML Table Rows in a TagHelper class to be added to a DataTables table that displays a few buttons in a hidden child row (shown on clicking a given row). 我正在努力在TagHelper类中生成HTML表行,以将其添加到DataTables表中,该表在隐藏的子行中显示一些按钮(单击给定行时显示)。 For one of these buttons, I need the value from a property within a different class (corresponding to a value in a separate database table). 对于这些按钮之一,我需要来自不同类中的属性的值(对应于单独数据库表中的值)。 I'm not sure how to go about referencing the other class so that it has the correct value for the given survey. 我不确定如何去引用其他类,以使其对于给定的调查具有正确的价值。 The class layout is something like this: 类的布局是这样的:

Relevant Snippet from the TagHelper class I'm working in: 我正在使用的TagHelper类的相关代码片段:

public IEnumerable<Survey> listSurv { get; set; }

foreach(Survey surv in listSurv) {
    //Row Construction Happening Before the Button

    //I need to reference the Report class here to get the ReportID (Id in the Report class).
    //Currently, I have this, but it always returns 0
    Report r = new Report();
    innerData.InnerHtml.Append(r.Id.ToString()); //innerData is a TagBuilder element that's previously constructed

}

The Report Class: 报告类别:

public class Report()
{
    public int Id {get; set;}
    public virtual Survey Survey {get; set;}
    public string DLLink {get; set;}
    public DateTime Date_Uploaded {get; set;}
}

Is there some way I can Instantiate the Report class within the TagHelper class in a way that lets me access the Id corresponding with that particular survey? 有什么方法可以实例化TagHelper类中的Report类,使我可以访问与该特定调查相对应的ID? My initial thought was a paremeterized constructor, but I'm not sure how to go about Implementing that in this particular case. 我最初的想法是使用参数化的构造函数,但是我不确定如何在这种特殊情况下实现它。 I'm more of a PHP Developer, so I'm not as familiar with how this would work in a ASP.NET setting. 我更多地是PHP开发人员,所以我不太熟悉如何在ASP.NET设置中工作。

You need a link back from Survey to Report . 您需要从SurveyReport的链接。 Without Survey code, that one is hard to tell. 没有Survey代码,很难说出来。 What you can do is save the report as a reference in the survey, and call that from your code. 您可以做的是将报告另存为调查中的参考,然后从代码中调用它。 What you did now is creating a new Report , such that is has always a default id of zero. 您现在要做的是创建一个新Report ,其默认ID始终为零。

So create a report reference in survey: 因此,在调查中创建报告参考:

public class Survey {
    public Report Report { get; set; }
}

Link the survey instance with a reference to the report instance: 将调查实例与对报表实例的引用链接起来:

var report = GetReport();
var survey = GetSurvey();
survey.Report = report;

Now you can retrieve report data from the report property: 现在,您可以从report属性检索报告数据:

foreach(Survey survey in listSurv) {
    innerData.InnerHtml.Append(survey.Report.Id.ToString());
}

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

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