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

Dav*_*ich 1 asp.net-mvc razor razor-declarative-helpers asp.net-mvc-3

这是我的模特

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; }
Run Code Online (Sandbox Code Playgroud)

这是我为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>                    
Run Code Online (Sandbox Code Playgroud)

让我们感到困惑的是,当没有选择部门时剃刀验证会抱怨.但学校模型没有[必需]属性.

"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>
Run Code Online (Sandbox Code Playgroud)

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

Zot*_*ote 10

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