gpt4 book ai didi

c# - MVC3 Unobtrusive Validation 不适用于自定义 DataAnnotations 属性

转载 作者:行者123 更新时间:2023-11-30 21:13:09 24 4
gpt4 key购买 nike

我有一个自定义属性,它目前是 DataAnnotations.RequiredAttribute 的简单包装器(稍后我将对其进行扩展,但只是暂时尝试让这个概念验证工作)。但是,这不适用于 MVC3 非侵入式验证。

这是一个非常简单的问题,真的。

这是我的自定义属性:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
public RequiredAttribute()
{
}

public RequiredAttribute(Type errorMessageResourceType, string errorMessageResourceName)
{
this.ErrorMessageResourceName = errorMessageResourceName;
this.ErrorMessageResourceType = errorMessageResourceType;
}
}

这里有两个模型属性,一个使用自定义属性,一个使用 DataAnnotations 属性:

[System.ComponentModel.DataAnnotations.Required]
public string FirstName { get; set; }

[CustomValidationAttributes.Required]
public string LastName { get; set; }

这是 Razor 代码:

<p>
@Html.TextBoxFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</p>
<p>
@Html.TextBoxFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</p>

这是结果输出:

<p>
<input type="text" value="" name="FirstName id="FirstName" data-val-required="The First Name field is required." data-val="true">
<span data-valmsg-replace="true" data-valmsg-for="FirstName" class="field-validation-valid"></span>
</p>
<p>
<input type="text" value="" name="LastName" id="LastName">
<span data-valmsg-replace="true" data-valmsg-for="LastName" class="field-validation-valid"></span>
</p>

如您所见,FirstName(使用 DataAnnotations)使用验证器所需的必要 html 属性呈现,但 LastName(使用 CustomValidationAttributes)缺少 data-val-required数据值属性

我是不是做错了什么,或者 MVC3 非侵入式验证不支持这种方式?

提前致谢。

最佳答案

正如 ingo 在上面的评论中指出的那样,我最终不得不实现 IClientValidatable 才能使它们正常工作。因此,在我上面的示例中,我必须将其添加到我的属性中:

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "required"
};

yield return modelClientValidationRule;
}

关于c# - MVC3 Unobtrusive Validation 不适用于自定义 DataAnnotations 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6988776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com