Jquery MaskMoney asp.net Mvc

1

I use Jquery MaskMoney in my inputs to treat decimais , so far so good, but I noticed that when I type values above 1,000,00 But when the value is a thousand where the point (999.99) does not go, the value arrives correct in MaskMoney follow my Bind and my Mvc :

Controller

[HttpPost]
public ActionResult Editar(Produto produto, string returnUrl)
{
    TempData["mensagem"] = "PRODUTO EDITADO COM SUCESSO!";
    if (!String.IsNullOrEmpty(produto.Cest))
    {
        produto.Cest = produto.Cest.Replace(".", "");
    }
    produto.Codigo = produto.Codigo.Split(Convert.ToChar("."))[1];
    ctx.Entry(produto).State = EntityState.Modified;
    ctx.SaveChanges();
    return Redirect("~" + returnUrl);
    //  return RedirectToAction("sucesso", "produto");
}

Controller

public decimal Custo { get; set; }

Model

<div class="col-lg-2">
   <label for="Custo">Custo</label>
   @Html.TextBoxFor(model => model.Custo, new { @class = "form-control decimal required" })
</div>
    
asked by anonymous 01.12.2016 / 18:09

1 answer

2

You will have to create your own Model Binder to handle this specific case of decimal number localization (Brazilian formatting).

follows an example class for this decimal model binder:

using System;
using System.Globalization;
using System.Web.Mvc;

public class DecimalModelBinder : IModelBinder {
    public object BindModel(ControllerContext controllerContext, 
        ModelBindingContext bindingContext) {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try {
            actualValue = Convert.ToDecimal(valueResult.AttemptedValue, 
                CultureInfo.CurrentCulture);
        }
        catch (FormatException e) {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
}

This class is extracting a decimal value from the parameters of the posted form and transforming it into decimal

Then, in order for MVC to use its binder class, simply add that line to the% method of% pain file Application_Start

like this:

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();

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

    // All that other stuff you usually put in here...
}

If you'd like to read more about this solution, have some more explanation, I found it on Phil Haack's blog: Model Binding Decimal Values

    
01.12.2016 / 19:34