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

Asked

Viewed 231 times

1

You guys, good morning.

I have a class that has a decimal field where I keep the price. So far so good. When it is displayed in the /Edit/ page, also ta beauty. But here’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 stating that the format is incorrect (EF validate). 2 - If I put the . 00, it passes 3 - if it is for some value of type: 14.90 (14.90 in real) it sends to the bank 14900

How could I solve this problem?

Follows 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>

2 answers

2

The way is to implement your own Model Binder. A Model Binder which 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());
        ...
    }
}

-2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.