【问题标题】:Validation for multiple objects some required some not验证多个对象有些需要有些不需要
【发布时间】:2017-07-04 13:03:02
【问题描述】:

我有这门课

    public class ComponentMarks
{
    public int Id { get; set; }
    public BuildingComponent ComponentType { get; set; }
    [Range(1, 3)]
    public int Stav { get; set; }
    [Range(1, 3)]
    public int NutnostInvestice { get; set; }
    [Range(1, 3)]
    public int OdhadVyseInvestice { get; set; }
    public string Note { get; set; }
}

我在课堂上使用的

    public ComponentMarks FasadaMarks { get; set; }
    [Required]
    public ComponentMarks StrechaMarks { get; set; }
    [Required]
    public ComponentMarks DvereOknaMarks { get; set; }
    [Required]
    public ComponentMarks VodaMarks { get; set; }


    public ComponentMarks PlynMarks { get; set; }
    [Required]
    public ComponentMarks ElektroinstalaceMarks { get; set; }
    [Required]
    public ComponentMarks OdpadyMarks { get; set; }
    [Required]
    public ComponentMarks TopeniMarks { get; set; }
    [Required]
    public ComponentMarks DatoveSiteMarks { get; set; }
    [Required]
    public ComponentMarks VnejsiRozvodyMarks { get; set; }

}

我希望除 PlynMarks 之外的所有内容都是必需的,但 PlynMarks 始终是必需的。我现在可以使 int 属性可以为空而不是必需的,但我怎样才能只为 plynmarks 做到这一点?我想在服务器端进行验证。

   <tr>
                <td>
                    <label>Plyn:</label>
                </td>
                <td>
                    @Html.TextBoxFor(x => x.PlynMarks.Stav, new {@Value = ""})
                    @Html.ValidationMessageFor(x => x.PlynMarks.Stav)
                </td>
                <td>
                    @Html.TextBoxFor(x => x.PlynMarks.NutnostInvestice, new {@Value = ""})
                    @Html.ValidationMessageFor(x => x.PlynMarks.NutnostInvestice)
                </td>
                <td>
                    @Html.TextBoxFor(x => x.PlynMarks.OdhadVyseInvestice, new { @Value = "" })
                    @Html.ValidationMessageFor(x => x.PlynMarks.OdhadVyseInvestice)
                </td>
                <td>
                    @Html.TextAreaFor(x => x.PlynMarks.Note, new {@Value = ""})
                </td>
            </tr>
            <tr>

感谢您的帮助。

【问题讨论】:

  • “我想要除 PlynMarks 之外的所有内容,但始终需要 PlynMarks”!这是什么意思?
  • 对不起,这意味着 PlynMarks 没有必需的属性,但它是必需的。我的临时解决方案是为componentMarks 设置两个类,一个是int?和一个正常的int。
  • 为什么不为 PlynMarks 添加“必需”?
  • 我认为最简单的方法是通过以下方式使 PlynMarks 为空:'public ComponentMarks? PlynMarks { 得到;放; }'
  • 当我尝试这个时,我得到了错误:类型 ComponentMarks 必须是不可为空的值类型才能将其用作泛型类型或方法 Nullable 中的参数 T

标签: c# asp.net asp.net-mvc validation


【解决方案1】:

我为 ComponentMarksNullable 列出了组件标记和属性,然后在控制器中检查 ComponentMarksNullabel 是否有值。如果它有值,我将它添加到列表,然后添加到 db。感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多