必须设置ErrorMessageString或ErrorMessageResourceName,但不能使用CreditCardAttribute同时设置错误

时间:2023-01-22 14:30:33

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

检查您的卡号是否正确

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,但不是两者都设置”。这种情况只发生在信用记录中。其他验证属性,如RequiredAttribute可以很好地工作。我只设置了ErrorMessageResourceName。我没有设置ErrorMessageString,所以不理解我做错了什么。谁能帮助好吗?

6 个解决方案

#1


149  

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

参考链接现在被断开了。http://connect.microsoft.com/VisualStudio/feedback/details/757298/emailaddress-attribute-is-unable-to-load-error-message-from-resource-mvc

#2


13  

[CreditCard(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "CardNumberInvalid", ErrorMessage = null)]

Adding the ErrorMessage = null will fix your problem.

添加ErrorMessage = null将修复您的问题。

#3


10  

I had this problem because I had implemented a RequiredAttributeAdapter, which was setting the ErrorMessageResourceName property automatically.

我遇到了这个问题,因为我实现了一个RequiredAttributeAdapter,它自动设置ErrorMessageResourceName属性。

You can fix it by checking to see if the ErrorMessage property has been set before setting the ErrorMessageResourceName:

您可以在设置ErrorMessageResourceName之前检查ErrorMessage属性是否设置好:

/// <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";
    }
}

#4


0  

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=null anymore 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 FormatErrorMessage instead.

正如您所看到的,不再需要添加ErrorMessage=null,因为我们在自定义验证类中已经处理过了。不要忘记,如果您在自定义验证中初始化了任何错误消息字符串,那么现在就必须删除它,并使用FormatErrorMessage。

#5


0  

I had a simmilar issue with a custom ValidationAttribute.

我有一个自定义validation属性的simmilar问题。

In the IsValid method I was setting the ErrorMessage. The fix was to remove the assignation to the ErrorMessage propety...

在IsValid方法中,我设置了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...

我正在编写单元测试,只有当我一个一个地运行/调试时,它们才是pasisng。但是当我点击“Run All”时,只有第一个在传递?它们之间没有任何联系……

So yeah, just remove the remove the assignation to the ErrorMessage propety

所以,只要移除错误消息的转让人

I hope it will help someone!

我希望它能帮助别人!

#6


-1  

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 ErrorMessage I fixed the problem.

在我的例子中,通过删除ErrorMessage我解决了这个问题。

#1


149  

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

参考链接现在被断开了。http://connect.microsoft.com/VisualStudio/feedback/details/757298/emailaddress-attribute-is-unable-to-load-error-message-from-resource-mvc

#2


13  

[CreditCard(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "CardNumberInvalid", ErrorMessage = null)]

Adding the ErrorMessage = null will fix your problem.

添加ErrorMessage = null将修复您的问题。

#3


10  

I had this problem because I had implemented a RequiredAttributeAdapter, which was setting the ErrorMessageResourceName property automatically.

我遇到了这个问题,因为我实现了一个RequiredAttributeAdapter,它自动设置ErrorMessageResourceName属性。

You can fix it by checking to see if the ErrorMessage property has been set before setting the ErrorMessageResourceName:

您可以在设置ErrorMessageResourceName之前检查ErrorMessage属性是否设置好:

/// <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";
    }
}

#4


0  

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=null anymore 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 FormatErrorMessage instead.

正如您所看到的,不再需要添加ErrorMessage=null,因为我们在自定义验证类中已经处理过了。不要忘记,如果您在自定义验证中初始化了任何错误消息字符串,那么现在就必须删除它,并使用FormatErrorMessage。

#5


0  

I had a simmilar issue with a custom ValidationAttribute.

我有一个自定义validation属性的simmilar问题。

In the IsValid method I was setting the ErrorMessage. The fix was to remove the assignation to the ErrorMessage propety...

在IsValid方法中,我设置了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...

我正在编写单元测试,只有当我一个一个地运行/调试时,它们才是pasisng。但是当我点击“Run All”时,只有第一个在传递?它们之间没有任何联系……

So yeah, just remove the remove the assignation to the ErrorMessage propety

所以,只要移除错误消息的转让人

I hope it will help someone!

我希望它能帮助别人!

#6


-1  

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 ErrorMessage I fixed the problem.

在我的例子中,通过删除ErrorMessage我解决了这个问题。