7

I've read answers about localization of validation errors by specifying DefaultModelBinder.ResourceClassKey, basically it's when entering string values in int field or not a datetime in datetime field.

But when I'm typing "111111111111111111111111111111" for an int field I get System.OverflowException and it looks like "The value '{0}' is invalid.".

Is there a way to localize (translate that message to other languages) that validation error in a way similar to other MVC-validation?

4

2 回答 2

4

I had the same issue, and I finally managed to find the solution. Yes, that message can be localized, and luckily it's pretty easy when you figure it out.

You have to create a resource file and put it in the App_GlobalResources folder. You can call the file whatever you want, but I usually call it MvcValidationMessages.

Open the resource file and create a string with the name InvalidPropertyValue and write whatever message you want in the value field.

Now, open the Global.asax file and add the following line to the method Application_Start():

System.Web.Mvc.Html.ValidationExtensions.ResourceClassKey = "MvcValidationMessages";  

"MvcValidationMessages" should of course be the correct name of the resource file you just created.

And voíla! That's all there is to it. The message shown will now be your own instead of the default one.

于 2013-02-03T11:08:08.437 回答
0

I ended up overriding ModelBinder for int and supplying a localized error-message there:

public class IntModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        double parsedValue;
        if (double.TryParse(value.AttemptedValue, out parsedValue))
        {
            if ((parsedValue < int.MinValue || parsedValue > int.MaxValue))
            {
                var error = "LOCALIZED ERROR MESSAGE FOR FIELD '{0}' HERE!!!";
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, string.Format(error, value.AttemptedValue, bindingContext.ModelMetadata.DisplayName));
            }
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

Then I simply registered it: ModelBinders.Binders.Add(typeof(int), new IntModelBinder()); and it now works fine.

P.S. sure, my localized errormessages are not hardcoded in model binder, this is just a simplified example :)

于 2012-06-11T06:12:32.883 回答