在 MVC 2 中向自定义数据注释属性显示自定义客户端错误消息
我在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论