验证多个对象,有些不需要

时间:2017-07-04 13:03:02

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

我有这个课程

    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之外都需要o,但总是需要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>

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我为ComponentMarksNullable创建了componentMarks和property的列表,然后在控制器中检查ComponentMarksNullabel是否有值。如果它有值,我将它添加到列表然后再添加到db。感谢您的帮助。