Wednesday, May 18, 2011

Cleaning up code smells

Worst code smells

  • Long classes
  • Duplicated code
  • Unused methods
  • Unnecessary casting
  • Overuse of design patterns

How to solve decimal binding problem in ASP.NET MVC

Phil Haack to the rescue! After doing some searching I stumbled across this post which fixes binding to string values with comma separators. It solves the same problem I'm having, so I'll repost the bits here:
using System;
using System.Globalization;
using System.Web.Mvc;
public class DecimalModelBinder : IModelBinder {
    public object BindModel(ControllerContext controllerContext,
                                    ModelBindingContext bindingContext) {
        ValueProviderResult valueResult = bindingContext.ValueProvider
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try {
            actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
        catch (FormatException e) {

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
Then stick this into your Global.asax.cs Application_Start:
protected void Application_Start() {
    ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    // Your other stuff goes here.
Once I did that and re-ran the code above, everything works as expected. See for yourself:

Model values after adding DecimalModelBinder