Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Adding a resource file to App_GlobalResources with a PropertyValueRequired key and changing DefaultModelBinder.ResourceClassKey to the file name has no effect on MVC 4. The string The {0} field is required is never changed. I don't want to set the resource class type and key on every required field. Am I missing something?

Edit:

I've made a small modification on Darin Dimitrov's code to keep Required customizations working:

public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
    public MyRequiredAttributeAdapter(
        ModelMetadata metadata,
        ControllerContext context,
        RequiredAttribute attribute
    )
        : base(metadata, context, attribute)
    {
        if (attribute.ErrorMessageResourceType == null)
        {
            attribute.ErrorMessageResourceType = typeof(Messages);
        }
        if (attribute.ErrorMessageResourceName == null)
        {
            attribute.ErrorMessageResourceName = "PropertyValueRequired";
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
447 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is not specific to ASP.NET MVC 4. It was the same in ASP.NET MVC 3. You cannot set the required message using DefaultModelBinder.ResourceClassKey, only the PropertyValueInvalid.

One way to achieve what you are looking for is to define a custom RequiredAttributeAdapter:

public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
    public MyRequiredAttributeAdapter(
        ModelMetadata metadata,
        ControllerContext context,
        RequiredAttribute attribute
    ) : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Messages);
        attribute.ErrorMessageResourceName = "PropertyValueRequired";
    }
}

that you will register in Application_Start:

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(RequiredAttribute),
    typeof(MyRequiredAttributeAdapter)
);

Now when a non-nullable field is not assigned a value, the error message will come from Messages.PropertyValueRequired where Messages.resx must be defined inside App_GlobalResources.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...