Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC 4 ignores DefaultModelBinder.ResourceClassKey

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...