客户端验证未针对RequiredIf触发

时间:2014-12-18 06:02:07

标签: c# jquery asp.net-mvc data-annotations

我正在使用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>

我实施的事情:

  1. 已安装的软件包: Install-Package ExpressiveAnnotations
  2. Global.asax

    中添加了以下代码
    DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof (RequiredIfAttribute), typeof (RequiredIfValidator));
    DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof (AssertThatAttribute), typeof (AssertThatValidator));
    
  3. jquery 验证文件下方的软件包中添加了 expressive.annotations.validate.js ,并在指定页面上添加了软件包。

1 个答案:

答案 0 :(得分:2)

我觉得很好。控制台输出有错误吗?

你可以尝试一下这对我有用的东西:

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