Custom Binder for decimals and integer: how to get string value before MVC and make more reasonable conversion

I want to expand the default model binding to be smarter when dealing with numbers. By default, it works very poorly when the game has commas and decimal points.

I tried to make a new binder

Public Class SmartModelBinder
    Inherits DefaultModelBinder
    Protected Overrides Sub SetProperty(controllerContext As ControllerContext, bindingContext As ModelBindingContext, propertyDescriptor As System.ComponentModel.PropertyDescriptor, value As Object)
        If propertyDescriptor.PropertyType Is GetType(Decimal) Or propertyDescriptor.PropertyType Is GetType(Decimal?) Then
            If value Is Nothing Then
                value = 0
            End If
        End If

        MyBase.SetProperty(controllerContext, bindingContext, propertyDescriptor, value)
    End Sub
End Class

But the value is already converted at this moment

How can I extend a binder to get a string value from a form and perform another conversion?

+3
source share
3 answers

How about this?

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder())

And a custom binder. I think I don’t know if you can override the decimal binding in this way, but it works for my own types.

public class DecimalModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult == null)
        {
            return base.BindModel(controllerContext, bindingContext);
        }
        // to-do: your parsing (get the text value from valueProviderResult.AttemptedValue)
        return parsedDecimal;
    }
}
+6
source

, , , , - BindModel. , , , :

public class MyModel
{
  public int Id;
  public string Name;
}

MVC MyModel, BindModel . , MyModel "" (.. int, decimal, string ..). , , , BindModel /, .

, , ( ). , , BindModel .

, , , ,

+2

I am adding an additional answer because Phil Haack recently wrote on how to do this. He warns that he is unchecked, but he uses ModelStateand, if necessary, adds an error, which I never knew about when / how to do this, so it was useful to me.

Here is a link to his post: http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx

+1
source

All Articles