在 MVC 2 中向自定义数据注释属性显示自定义客户端错误消息

发布于 2024-12-21 04:48:40 字数 3537 浏览 3 评论 0原文

我在 MVC 2 中创建了一个名为 RemoteVal 的自定义远程数据注释属性,如下所示

public class remoteValAttribute:ValidationAttribute
{
    public string Action { get; set; }
    public string Controller { get; set; }
    public string ParameterName { get; set; }
    public string RouteName { get; set; }

    public override bool IsValid(object value)
    {
        return true;
    }
}

适配器类

public class RemoteAttributeAdapter:DataAnnotationsModelValidator<remotevalAttribute>
{
    public RemoteAttributeAdapter(ModelMetadata metadata, ControllerContext context, remoteVal attribute) : base(metadata, context, attribute) { }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        ModelClientValidationRule rule = new ModelClientValidationRule()
        {
            ErrorMessage = ErrorMessage,
            ValidationType = "remoteVal"
        };

        rule.ValidationParameters["url"] = GetUrl();
        rule.ValidationParameters["parameterName"] = Attribute.ParameterName;
        return new ModelClientValidationRule[] { rule };
    }

    private string GetUrl()
    {
        RouteValueDictionary rvd = new RouteValueDictionary(){
            {"controller",Attribute.Controller},
            {"action",Attribute.Action}
        };

        var virtualPath = RouteTable.Routes.GetVirtualPath(ControllerContext.RequestContext, Attribute.RouteName, rvd);
        if (virtualPath == null)
        {
            throw new InvalidOperationException("No route matched!");
        }

        return virtualPath.VirtualPath;
    }
}

在模型类中添加了属性

[Required(ErrorMessage = "Title Required")]
[remoteVal(Controller = "Validation", Action = "IsTitle_Available", ParameterName = "Title")]
[ScaffoldColumn(false)]
public object Title { get; set; }

添加了 jQuery 脚本,如下所示

<script type="text/javascript" src="../../Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcJQueryValidation.js"></script>
<script type="text/javascript">
        $(function () {
            var ermessage = '';
            jQuery.validator.addMethod("remoteVal", function (value, element, params) {
                var validator = this;
                var valid = false;
                if (this.optional(element)) {
                    return true;
                }
                else {
                    var url = params.url;
                    var parameterName = params.parameterName;

                    var newUrl = ((url.indexOf('?') < 0) ? (url + '?') : (url + '&'))
                                + encodeURIComponent(parameterName) + '=' + encodeURIComponent(value);

                    var response = $.ajax({
                        url: newUrl,
                        async: false
                    }).responseText;

                    if (response == 'OK')
                        valid = true;
                    else {
                        valid = false;
                        var errors = {};
                        errors[element.name] = response;
                        validator.showErrors(errors);
                    }
                }
                return valid;
            });
        });
</script>

如果标题已注册,来自 AJAX 调用的响应将显示为错误消息。但错误始终显示为字段标题无效。请帮助我解决这个问题。

I have created a custom remote data annotation attribute called remoteVal in MVC 2 as below

public class remoteValAttribute:ValidationAttribute
{
    public string Action { get; set; }
    public string Controller { get; set; }
    public string ParameterName { get; set; }
    public string RouteName { get; set; }

    public override bool IsValid(object value)
    {
        return true;
    }
}

Adapter class

public class RemoteAttributeAdapter:DataAnnotationsModelValidator<remotevalAttribute>
{
    public RemoteAttributeAdapter(ModelMetadata metadata, ControllerContext context, remoteVal attribute) : base(metadata, context, attribute) { }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        ModelClientValidationRule rule = new ModelClientValidationRule()
        {
            ErrorMessage = ErrorMessage,
            ValidationType = "remoteVal"
        };

        rule.ValidationParameters["url"] = GetUrl();
        rule.ValidationParameters["parameterName"] = Attribute.ParameterName;
        return new ModelClientValidationRule[] { rule };
    }

    private string GetUrl()
    {
        RouteValueDictionary rvd = new RouteValueDictionary(){
            {"controller",Attribute.Controller},
            {"action",Attribute.Action}
        };

        var virtualPath = RouteTable.Routes.GetVirtualPath(ControllerContext.RequestContext, Attribute.RouteName, rvd);
        if (virtualPath == null)
        {
            throw new InvalidOperationException("No route matched!");
        }

        return virtualPath.VirtualPath;
    }
}

Added the attribute in the model class

[Required(ErrorMessage = "Title Required")]
[remoteVal(Controller = "Validation", Action = "IsTitle_Available", ParameterName = "Title")]
[ScaffoldColumn(false)]
public object Title { get; set; }

Added the jQuery script as below

<script type="text/javascript" src="../../Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcJQueryValidation.js"></script>
<script type="text/javascript">
        $(function () {
            var ermessage = '';
            jQuery.validator.addMethod("remoteVal", function (value, element, params) {
                var validator = this;
                var valid = false;
                if (this.optional(element)) {
                    return true;
                }
                else {
                    var url = params.url;
                    var parameterName = params.parameterName;

                    var newUrl = ((url.indexOf('?') < 0) ? (url + '?') : (url + '&'))
                                + encodeURIComponent(parameterName) + '=' + encodeURIComponent(value);

                    var response = $.ajax({
                        url: newUrl,
                        async: false
                    }).responseText;

                    if (response == 'OK')
                        valid = true;
                    else {
                        valid = false;
                        var errors = {};
                        errors[element.name] = response;
                        validator.showErrors(errors);
                    }
                }
                return valid;
            });
        });
</script>

If the Title is already registered, Response from AJAX call is to be shown as the error message. But the error is always shown as The field Title is invalid. Please help me in resolving this issue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文