Jquery Maskmoney Asp.net Mvc

Asked

Viewed 426 times

1

I use the Jquery MaskMoney in my inputs to treat the decimais, so far so good, but I noticed that when I type values above 1,000.00 where the MaskMoney plays me the point(.) in value, When I save the Bind of Mvc brings me that value Zeroed. But when the value is up thousand where the dot (999.99) the value arrives correct in Controller follows my Controller and my Model:

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");
}

Model

public decimal Custo { get; set; }

View

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

1 answer

2


You’ll have to create your own Model Binder to deal with this specific case of decimal number conversion with location (the Brazilian formatting).

follows an example class for this decimal Binder model:

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 posted form parameters and transforming it into value decimal

Then, for the MVC to use its Binder class, just add this line in the method Application_Start pain file Global.asax.cs

thus:

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

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

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

If you want to read a little more about this solution, have some more explanation, I found it on Phil Haack’s blog: Model Binding Decimal Values

  • 1

    Sensational , it worked perfectly. Thank you very much

Browser other questions tagged

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