Localization for "value {0} is invalid" in case of int overflow

I read the answers about the localization of validation errors, indicating DefaultModelBinder.ResourceClassKeymainly when entering string values ​​in the int field or not in the datetime in the datetime field.

But when I type "1111111111111111111111111111111111" for the int field, I get System.OverflowExceptionand it looks like "The value '{0}' is invalid.".

Is there a way to localize (translate this message into other languages) that the validation error is similar to MVC verification?

+5
source share
2 answers

, . , , , , , .

App_GlobalResources. , , MvcValidationMessages.

InvalidPropertyValue .

Global.asax Application_Start():

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

"MvcValidationMessages" , , .

! , . , .

+3

ModelBinder int :

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);
    }
}

: ModelBinders.Binders.Add(typeof(int), new IntModelBinder()); .

P.S. , , :)

0

All Articles