没有[required]属性的剃刀验证触发

时间:2013-01-18 16:52:27

标签: asp.net-mvc asp.net-mvc-3 razor razor-declarative-helpers

这是我的模特

public class SchoolUser
{
    public int schoolId { get; set; }

    public int contact1UserId { get; set; }

    public IEnumerable<DataLayer.salutations> Salutations { get; set; }

    public int departmentId { get; set; }

    public IEnumerable<DataLayer.departments> Departments { get; set; }

    [Required]
    public int roleId { get; set; }

    public IEnumerable<DataLayer.rolesView> roles { get; set; }

这是我为deptartmentid视图创建下拉列表的剃刀代码

                <div style="width:75%; display:inline-block; margin-left:5px;">
                    @Html.DropDownListFor(model => model.departmentId, new SelectList(Model.Departments, "deptId", "description"), "")
                    @Html.ValidationMessageFor(model => model.departmentId)
                </div>                    

什么让我们感到困惑,剃刀验证在没有选择部门的情况下抱怨。但学校模型没有[必需]属性。

“departmentId字段是必需的。”

查看页面源我看到了

 <select data-val="true" data-val-number="The field departmentId must be a number." data-val-required="The departmentId field is required." id="departmentId" name="departmentId"><option value=""></option>
<option value="30">English</option>
</select>

出于某种原因,剃刀视图引擎已“决定”要求填充此字段,即使模型没有[required]或其他约束属性。

1 个答案:

答案 0 :(得分:10)

它不可空。 你应该把它改成int?