我的类在ASP.NET MVC中的Form Post上变空

时间:2016-08-15 13:01:16

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

我目前正在研究C#中的面向对象编程(OOP),最近发现由于灵活性,Composition比继承更受青睐。不管怎样,我现在正在购买。

我有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 View 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时的实现。

2 个答案:

答案 0 :(得分:0)

而不是:

public readonly Student Student = new Student();

使用

public Student Student = new Student();

readonly使您的财产不可编辑

答案 1 :(得分:0)

将模型添加到视图标题中 @model学生

并从类

的初始化中删除readonly

公共课程技能评估 {

public Student _student {get;set;}
[Required]
public string Industry { get; set; }
[Required]
public string YearsInIndustry { get; set; }

}

然后在您的操作中初始化Student类,然后再将其发送到视图。