How to set decimal separators in ASP.NET MVC controllers?

前端 未结 4 1249
花落未央
花落未央 2020-11-29 23:39

I\'m working with the NerdDinner application trying to teach myself ASP.NET MVC. However, I have stumbled upon a problem with globalization, where my server presents floatin

4条回答
  •  清歌不尽
    2020-11-30 00:10

    I have a different take on this, you might like it. What I don't like about the accepted answer is it doesn't check for other characters. I know there will be a case where the currency symbol will be in the box because my user doesn't know better. So yeah I can check in javascript to remove it, but what if for some reason javascript isn't on? Then extra characters might get through. Or if someone tries to spam you passing unknown characters through... who knows! So I decided to use a regex. It's a bit slower, tiny fraction slower - for my case it was 1,000,000 iterations of the regex took just under 3 seconds, while around 1 second to do a string replace on a coma and period. But seeing as I don't know what characters might come through, then I am happy for this slightest of performance hits.

    public class DecimalModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext,
                                         ModelBindingContext bindingContext)
        {
            string modelName = bindingContext.ModelName;
            string attemptedValue =
                bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;
    
            if (bindingContext.ModelMetadata.IsNullableValueType
                    && string.IsNullOrWhiteSpace(attemptedValue))
            {
                return null;
            }
    
            if (string.IsNullOrWhiteSpace(attemptedValue))
            {
                return decimal.Zero;
            }
    
            decimal value = decimal.Zero;
            Regex digitsOnly = new Regex(@"[^\d]", RegexOptions.Compiled);
            var numbersOnly = digitsOnly.Replace(attemptedValue, "");
            if (!string.IsNullOrWhiteSpace(numbersOnly))
            {
                var numbers = Convert.ToDecimal(numbersOnly);
                value = (numbers / 100m);
    
                return value;
            }
            else
            {
                if (bindingContext.ModelMetadata.IsNullableValueType)
                {
                    return null;
                }
    
            }
    
            return value;
        }
    }
    

    Basically, remove all characters that are not digits, for a string that isn't empty. Convert to decimal. Divide by 100. Return result.

    Works for me.

提交回复
热议问题