【发布时间】:2016-08-15 13:01:15
【问题描述】:
我目前正在学习 C# 中的面向对象编程 (OOP),最近看到由于灵活性,组合比继承更受青睐。反正我现在有货。
我有 2 个班级(学生和评估)
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class SkillsAssessment
{
public readonly Student Student = new Student();
[Required]
public string Industry { get; set; }
[Required]
public string YearsInIndustry { get; set; }
}
我有一个 Razor 查看 StudentDetails.cshtml
@Html.TextBoxFor(x => x.Student.FirstName, htmlAttributes: new { @class = "form-control input-lg", @required = "required" })
@Html.TextBoxFor(x => x.Student.LastName, htmlAttributes: new { @class = "form-control input-lg", @required = "required" })
@Html.TextBoxFor(x => x.Industry, htmlAttributes: new { @class = "form-control input-lg", @required = "required" })
@Html.TextBoxFor(x => x.YearsInIndustry, htmlAttributes: new { @class = "form-control input-lg", @required = "required" })
在我的控制器中
Public ActionResult(SkillsAssessment data){
//This is where the problem comes
//Because the Student Class inside my SkillsAssessment is always null
//And all I can get is the Industry and YearsInIndustry field
}
我希望你能帮助我确定如何解决这个问题,并让我清楚地了解我的 Composition 实现。
【问题讨论】:
-
它必须是属性,而不是字段 -
public Student Student { get; set; }(旁注:删除@required="required"并使用@Html.ValidationMessageFor(...)) -
@StephenMuecke 您好,先生,如果这是一个重复的问题,我很抱歉,您能把另一个问题的链接发给我吗?您对我的问题的解决方案也确实有效,尽管我对我看到的组合优于继承的主题并不感到困惑。我认为我的作文是正确的。
-
你是什么意思另一个链接? (你指的是哪一个?)
-
刚刚看到您将我的问题标记为重复..
标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor