MVC 3 client side validation, model binding decimal value and culture (different decimal separator)

后端 未结 3 1712
一向
一向 2020-12-14 03:45

I am trying to have my client side validation (model binding) to support different cultures, and I found an interesting blog on the subject on which I am trying to implement

3条回答
  •  情书的邮戳
    2020-12-14 04:39

    Try this it's slightly modified version:

     public class DecimalModelBinder : IModelBinder
        {
            public object BindModel(ControllerContext controllerContext,
                ModelBindingContext bindingContext)
            {
                ValueProviderResult valueResult = bindingContext.ValueProvider
                    .GetValue(bindingContext.ModelName);
                ModelState modelState = new ModelState { Value = valueResult };
                object actualValue = null;
                try
                {
                    //if with period use InvariantCulture
                    if (valueResult.AttemptedValue.Contains("."))
                    {
                        actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                        CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        //if with comma use CurrentCulture
                        actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                        CultureInfo.CurrentCulture);
                    }
    
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }
    
                bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
                return actualValue;
            }
        }
    

    It works for me.

    UPDATE

    If you're using a partial view use $.validate.unobtrusive.parse("#selector") to reapply validation. If not try setting a globalization in your web.config (one in the root, not in the Views) to something like this:

    
      
        
      
    
    

    I have globalization set to Hr where we use comma as delimiters but with the DecimalModelBinder i have posted it will properly parse decimal or comma. Regards

提交回复
热议问题