我的类成为空的表单Post在ASP.净MVC

本文关键字:Post ASP MVC 表单 我的 | 更新日期: 2023-09-27 18:02:23

我目前正在学习c#中的面向对象编程(OOP),最近发现由于灵活性,组合比继承更受欢迎。不管怎样,我现在有现货。

我有两个班(学生和评估)

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" })

在我的Controller

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
}

我希望你能帮助我确定如何解决这个问题,并让我清楚地了解我的实现与组成。

我的类成为空的表单Post在ASP.净MVC

添加一个模型到视图标题@ model学生

并从类

的初始化中删除readonly

公共类SkillsAssessment{

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

}

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

而不是:

public readonly Student Student = new Student();
使用

public Student Student = new Student();

readonly使你的属性不可编辑