asp.net MVC 1.0 and 2.0 currency model binding
Asked Answered
G

1

5

I would like to create model binding functionality so a user can enter ',' '.' etc for currency values which bind to a double value of my ViewModel.

I was able to do this in MVC 1.0 by creating a custom model binder, however since upgrading to MVC 2.0 this functionality no longer works.

Does anyone have any ideas or better solutions for performing this functionality? A better solution would be to use some data annotation or custom attribute.

public class MyViewModel
{
    public double MyCurrencyValue { get; set; }
}

A preferred solution would be something like this...

public class MyViewModel
{
    [CurrencyAttribute]
    public double MyCurrencyValue { get; set; }
}

Below is my solution for model binding in MVC 1.0.

public class MyCustomModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        object result = null;

        ValueProviderResult valueResult;
        bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out valueResult);
        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueResult);

        if (bindingContext.ModelType == typeof(double))
        {
            string modelName = bindingContext.ModelName;
            string attemptedValue = bindingContext.ValueProvider[modelName].AttemptedValue;

            string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
            string alternateSeperator = (wantedSeperator == "," ? "." : ",");

            try
            {
                result = double.Parse(attemptedValue, NumberStyles.Any);
            }
            catch (FormatException e)
            {
                bindingContext.ModelState.AddModelError(modelName, e);
            }
        }
        else
        {
            result = base.BindModel(controllerContext, bindingContext);
        }

        return result;
    }
}
Gonad answered 16/3, 2010 at 10:36 Comment(0)
I
7

You might try something among the lines:

// Just a marker attribute
public class CurrencyAttribute : Attribute
{
}

public class MyViewModel
{
    [Currency]
    public double MyCurrencyValue { get; set; }
}


public class CurrencyBinder : DefaultModelBinder
{
    protected override object GetPropertyValue(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext, 
        PropertyDescriptor propertyDescriptor, 
        IModelBinder propertyBinder)
    {
        var currencyAttribute = propertyDescriptor.Attributes[typeof(CurrencyAttribute)];
        // Check if the property has the marker attribute
        if (currencyAttribute != null)
        {
            // TODO: improve this to handle prefixes:
            var attemptedValue = bindingContext.ValueProvider
                .GetValue(propertyDescriptor.Name).AttemptedValue;
            return SomeMagicMethodThatParsesTheAttemptedValue(attemtedValue);
        }
        return base.GetPropertyValue(
            controllerContext, 
            bindingContext, propertyDescriptor, 
            propertyBinder
        );
    }
}

public class HomeController: Controller
{
    [HttpPost]
    public ActionResult Index([ModelBinder(typeof(CurrencyBinder))] MyViewModel model)
    {
        return View();
    }
}

UPDATE:

Here's an improvement of the binder (see TODO section in previous code):

if (!string.IsNullOrEmpty(bindingContext.ModelName))
{
    var attemptedValue = bindingContext.ValueProvider
        .GetValue(bindingContext.ModelName).AttemptedValue;
    return SomeMagicMethodThatParsesTheAttemptedValue(attemtedValue);
}

In order to handle collections you will need to register the binder in Application_Start as you will no longer be able to decorate the list with the ModelBinderAttribute:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.Add(typeof(MyViewModel), new CurrencyBinder());
}

And then your action could look like this:

[HttpPost]
public ActionResult Index(IList<MyViewModel> model)
{
    return View();
}

Summarizing the important part:

bindingContext.ValueProvider.GetValue(bindingContext.ModelName)

A further improvement step of this binder would be to handle validation (AddModelError/SetModelValue)

Inboard answered 16/3, 2010 at 10:52 Comment(1)
If you are dealing with a list of MyViewModel does that change the ModelBinder for the action? public ActionResult Index([ModelBinder(typeof(CurrencyBinder))] IList<MyViewModel> model)Gonad

© 2022 - 2024 — McMap. All rights reserved.