EF 6 Code First: Decimal field gives error when trying to save

1

Hello, good morning.

I have a class that has a decimal field where I save the price. So far so good. When it is displayed in the / Edit / of the page, it is also beauty. But that's the problem: 1 - The MVC (which I am using 4 with EF 6) it displays in the input the field with, 00 then when I save it does not leave informing that the format is incorrect (EF validate). 2 - If I put the .00, it passes 3 - if it is for some value of the type: 14.90 (14.90 in real) it sends to the bank 14900

How could you solve this problem?

Follow the class:

public class Opcional
{
    public Opcional()
    {
        this.Diarias = new HashSet<Diaria>();
    }
    [Key]
    public int OpcionalId { get; set; }

    [Required]
    public String Descricao { get; set; }

    [Required]
    public decimal Valor { get; set; }

    public virtual ICollection<Diaria> Diarias { get; private set; }
}

Excerpt from my edit code:

<div class="col-md-12">
        <div class="col-md-2">@Html.LabelFor(model => model.Valor)</div>
        <div class="col-md-10">
            @Html.EditorFor(model => model.Valor)
            @Html.ValidationMessageFor(model => model.Valor)
        </div>
    </div>
    
asked by anonymous 04.07.2015 / 10:30

1 answer

2

The way is to implement your own Model Binder . A Model Binder that I use for decimals is below:

public class DecimalModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {

        object result = null;

        string modelName = bindingContext.ModelName;
        string attemptedValue = bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;

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

        if (attemptedValue.IndexOf(wantedSeperator) == -1
            && attemptedValue.IndexOf(alternateSeperator) != -1)
        {
            attemptedValue = attemptedValue.Replace(alternateSeperator, wantedSeperator);
        }

        try
        {
            result = decimal.Parse(attemptedValue, NumberStyles.Any);
        }
        catch (FormatException e)
        {
            bindingContext.ModelState.AddModelError(modelName, e);
        }

        return result;
    }
}

Create this class in your project and register the class in Global.asax.cs :

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ...

        ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
        ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
        ...
    }
}
    
05.07.2015 / 06:00