2

Possible Duplicate:
How to filter form data with custom model binder

The simple model below pre-populates fields as desired in an edit/create view (i.e., $250,000 & 75%). However, when posting back into the controller, the properties fail to bind properly.

What is the most simple way to get MVC to convert those strings from human friendly format back into decimal and float property values? Can I use some sort of ValueConverter attribute on my properties? Or do I have to implement a full up ModelBinder?

public class MyModel
{
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:C0}")]
    [Required]
    [Display(Name = "My Money")]
    public decimal Moo { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0%}")]
    [Required]
    [Display(Name = "Percentage of Awesomeness")]
    public float PercentAwesome { get; set; }
}

I had assumed incorrectly that the MVC Runtime would be able to handle it automagically by using the values in the DisplayFormat attribute.

Thanks in advance from an MVC newbie!

Community
  • 1
  • 1
Jason
  • 4,897
  • 2
  • 33
  • 40

1 Answers1

2

You'll need a custom model binder to do what you want. See this question for guidance.

Community
  • 1
  • 1
amurra
  • 15,221
  • 4
  • 70
  • 87
  • Oops. The solution pointed to by the link does not work for mvc3. – Jason Feb 11 '11 at 06:58
  • 1
    This one does though. [link](http://stackoverflow.com/questions/999791/decimal-values-with-thousand-separator-in-asp-net-mvc) – Jason Feb 11 '11 at 07:43
  • Nice blog about this issue/behavior. http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx – Jason Jul 01 '11 at 03:13