【问题标题】:My Class becomes empty on Form Post in ASP.NET MVC [duplicate]我的班级在 ASP.NET MVC 中的表单发布上变为空 [重复]
【发布时间】: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


【解决方案1】:

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

并从类的初始化中删除只读

公开课技能评估 {

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

}

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

【讨论】:

  • 是的,我的视图中已经有一个@model,这就是为什么我可以获取 Industry 和 YearsInIndustry 字段的值,除了学生类中的字段。因为当代码进入 Controller 时,Student 类会重新初始化,这就是它再次变为空的原因。不知道怎么解决。
  • @jmaghuyop 请检查我已经更新的答案
  • 我已经用你建议的解决了这个问题,我现在只是好奇它是否仍然遵循面向对象编程中的组合设计?
  • @jmaghuyop 是的。请把答案标记为正确:)
【解决方案2】:

代替:

public readonly Student Student = new Student();

使用

public Student Student = new Student();

readonly 使您的属性不可编辑

【讨论】:

  • 我已经尝试过使用 readonly 并且您建议的那个仍然无法正常工作。当代码进入 Controller 时,Student 类会重新初始化,这就是它再次变为空的原因。不知道怎么解决。
猜你喜欢
  • 1970-01-01
  • 2018-05-23
  • 2015-12-14
  • 1970-01-01
  • 2017-01-18
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多