c# – 不会为RequiredIf触发客户端验证

我在
JaroslawWaliszko之前使用ExpressiveAnnotations.当我通过ModelState.IsValid检查服务器端时,它工作正常.但它没有显示客户端验证消息.我不知道缺少什么.我也添加了jquery文件.这是我申请了RequiredIf的财产:

// When Role = Assistant Professor(which has id = 3), 
// His/ Her head's Id should be selected as ParentID.

[RequiredIf("RoleID == 3", ErrorMessage = "Select Head.")] 
public Nullable<int> ParentID { get; set; }

呈现的HTML如下:

<select class="form-control ng-pristine ng-valid" 
        data-val="true" 
        data-val-number="The field ParentID must be a number." 
        data-val-requiredif="Select Head." 
        data-val-requiredif-allowempty="false" 
        data-val-requiredif-constsmap="{}" 
        data-val-requiredif-expression="RoleID == 3" 
        data-val-requiredif-fieldsmap="{"RoleID":"numeric"}" 
        id="ParentID" 
        name="ParentID" 
        ng-model="DTO.ParentID" 
        ng-options="obj.Value as obj.Text for obj in headList">

    <option selected="selected" value="" class="">--select--</option>
    <option value="0">Mr. Kevin Thomas</option>
    <option value="1">Ms. Lisa Brown</option>
    <option value="2">Mr. Sail Kapoor</option>
</select>

我实施的事情:

>已安装的软件包:Install-Package ExpressiveAnnotations,
>在Global.asax中添加了以下代码

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof (RequiredIfAttribute), typeof (RequiredIfValidator));
DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof (AssertThatAttribute), typeof (AssertThatValidator));

>在jquery验证文件下面的bundle中添加了expressive.annotations.validate.js,并在指定页面上添加了bundle.

最佳答案 它看起来对我很好.控制台输出有错误吗?

你可以试试这对我有用:

public class Model
{
    public IEnumerable<SelectListItem> Supervisors
    {
        get
        {
            return new[]
            {
                new SelectListItem {Text = "Mr. Kevin Thomas", Value = "0"},
                new SelectListItem {Text = "Ms. Lisa Brown", Value = "1"},
                new SelectListItem {Text = "Mr. Sail Kapoor", Value = "2"}
            };
        }
    }

    [RequiredIf("RoleID == 3", ErrorMessage = "Select Head.")]
    public int? ParentID { get; set; }
    ...

并查看:

@Html.DropDownListFor(model => model.ParentID, Model.Supervisors, "--select--")
@Html.ValidationMessageFor(model => model.ParentID)

另外,除非你已经看过它,看看sample project,你可以找到几个类似的案例.

更新:

Look here for few troubleshooting steps.

点赞