asp.net-mvc 必须设置 ErrorMessageString 或 ErrorMessageResourceName,但不能同时设置使用 CreditCardAttribute 的错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12474876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Either ErrorMessageString or ErrorMessageResourceName must be set, but not both error using CreditCardAttribute
提问by isxpjm
This is my model:
这是我的模型:
namespace MvcApplication2.Models
{
public class CreditCard
{
[CreditCard(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "CardNumberInvalid")]
public string CardNumber { get; set; }
}
}
This is my Messages.resx:
这是我的 Messages.resx:
Name Value
名称值
CardNumberInvalid Check your card number is correct
CardNumberInvalid 检查您的卡号是否正确
And this is my view:
这是我的观点:
@model MvcApplication2.Models.CreditCard
@Html.TextBoxFor(m => m.CardNumber);
In MVC version 3 this works without error. In MVC 4 when I go to this page I get an excpetion saying "Either ErrorMessageString or ErrorMessageResourceName must be set, but not both". This is only happening with the CreditCardAttribute. Other validation attributes such as RequiredAttribute work fine. I have only set the ErrorMessageResourceName. I have not set the ErrorMessageString, so do not understand what I have done wrong. Can anyone help please?
在 MVC 版本 3 中,这可以正常工作。在 MVC 4 中,当我转到此页面时,我收到一条异常消息,说“必须设置 ErrorMessageString 或 ErrorMessageResourceName,但不能同时设置两者”。这只发生在 CreditCardAttribute 上。其他验证属性(例如 RequiredAttribute)工作正常。我只设置了 ErrorMessageResourceName。我没有设置ErrorMessageString,所以不明白我做错了什么。有人可以帮忙吗?
回答by Dipen Bhikadya
It's a known issue in .Net 4.5. Adding "ErrorMessage = null" named parameter should solve this.
这是 .Net 4.5 中的一个已知问题。添加“ErrorMessage = null”命名参数应该可以解决这个问题。
Reference:
Reference link is broken now.
http://connect.microsoft.com/VisualStudio/feedback/details/757298/emailaddress-attribute-is-unable-to-load-error-message-from-resource-mvc
回答by Ahm3d Said
[CreditCard(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "CardNumberInvalid", ErrorMessage = null)]
Adding the ErrorMessage = nullwill fix your problem.
添加ErrorMessage = null将解决您的问题。
回答by Ian Newson
I had this problem because I had implemented a RequiredAttributeAdapter, which was setting the ErrorMessageResourceNameproperty automatically.
我遇到这个问题是因为我实现了一个RequiredAttributeAdapter,它会ErrorMessageResourceName自动设置属性。
You can fix it by checking to see if the ErrorMessage property has been set before setting the ErrorMessageResourceName:
您可以通过在设置之前检查是否已设置 ErrorMessage 属性来修复它ErrorMessageResourceName:
/// <summary>
/// Creates a new instance of the RequiredAttributeAdapter, used for switching the default required message
/// format
/// </summary>
public CustomMessageRequiredAttributeAdapter(
ModelMetadata metadata,
ControllerContext context,
RequiredAttribute attribute
)
: base(metadata, context, attribute)
{
if (string.IsNullOrEmpty(attribute.ErrorMessage))
{
attribute.ErrorMessageResourceType = typeof (ValidationMessages);
attribute.ErrorMessageResourceName = "PropertyValueRequired";
}
}
回答by Amin K
Since anyone who is using custom validation attributes and also wants to load error messages from resources for localization purposes, would face this problem i share my workaround here.
assume that you have a custom validation attribute like this one
由于任何使用自定义验证属性并希望从资源加载错误消息以进行本地化目的的人都会面临这个问题,我在这里分享我的解决方法。
假设您有一个像这样的自定义验证属性
[FileTypeMustBe("jpg")]
public HttpPostedFileBase MyFile {get; set;}
in your custom validation attribute add this code
在您的自定义验证属性中添加此代码
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
ErrorMessageString, name, ValidFileType);
}
ValidFileType is name of a property which takes the input argument of custom validation attribute (jpg here),well now we can decorate our model property the way we like it to be
ValidFileType 是一个属性的名称,它接受自定义验证属性的输入参数(此处为 jpg),现在我们可以按照我们喜欢的方式装饰我们的模型属性
[FileTypeMustBe("jpg", ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "WrongFileTypeError")]
public HttpPostedFileBase MyFile {get; set;}
as you see there's no need to add ErrorMessage=nullanymore cause we took care of it in custom validation class. just do not forget if you had initialized any error message string in your custom validation , you have to remove it now and use FormatErrorMessageinstead.
如您所见,无需再添加ErrorMessage=null,因为我们在自定义验证类中处理了它。只是不要忘记如果您在自定义验证中初始化了任何错误消息字符串,您必须立即将其删除并使用FormatErrorMessage。
回答by Iannick
I had a simmilar issue with a custom ValidationAttribute.
我有一个自定义 ValidationAttribute 的类似问题。
In the IsValid method I was setting the ErrorMessage. The fix was to remove the assignation to the ErrorMessage propety...
在 IsValid 方法中,我设置了 ErrorMessage。修复是删除对 ErrorMessage 属性的分配...
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//code before ...
this.ErrorMessage = this.FormatErrorMessage(validationContext.DisplayName); //NOT GOOD...
ValidationResult validationResult = new ValidationResult(this.ErrorMessage, //And using the ErrorMessage Here...
new[] { validationContext.MemberName });
return validationResult;
}
I was writting Unit test and they were pasisng only if i was running/debugging one by one. But when I click "Run All", only the first one was passing? They are not Linked in any ways...
我正在编写单元测试,并且只有在我一一运行/调试时它们才会出现。但是当我点击“全部运行”时,只有第一个通过?他们没有以任何方式链接......
So yeah, just remove the remove the assignation to the ErrorMessage propety
所以是的,只需删除删除对 ErrorMessage 属性的分配
I hope it will help someone!
我希望它会帮助某人!
回答by Flea
I had this same problem on a property that I was localizing. I had defined the ErrorMessageResourceType and then the ErrorMessageResourceName but by mistake put the ErrorMessage atrtribute on as well which threw the exception
我在本地化的属性上遇到了同样的问题。我已经定义了 ErrorMessageResourceType 然后是 ErrorMessageResourceName 但错误地将 ErrorMessage 属性也放在了上面,这引发了异常
[NotEqualTo("User_Name", ErrorMessageResourceType = typeof(LROResources.Global), ErrorMessageResourceName = "UserPasswordCannotBeUsername", ErrorMessage = "The password cannot be the same as your Username.")]
So in my case by just removing ErrorMessageI fixed the problem.
因此,在我的情况下,只需删除即可ErrorMessage解决问题。

