MVC 5 Razor Number Format

Viewed 15
    [DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
    public decimal AmpereFee {
        get {
            return this._ampereFee;
        }
        set {
            this._ampereFee = value;
        }
    }

and in the view

       @Html.EditorFor(model => model.AmpereFee, new { htmlAttributes = new { @class = "form-control" } })

When I first load the page, the number is perfectly shown:

enter image description here

I have two problems: First one, when I click submit , I have the following error: enter image description here

The second error is that when I edit the number it does not display correctly, as in the below image. enter image description here

what are the solutions for these two problems?

1 Answers

I found the answer after hours of searching:

  1. For stopping the error we need to create a custom model binder so create this class:

    using System;
    

using System.Web.Mvc;

namespace SLibWeb.ModelBinder
{
    public class SDecimalModelBinder : 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;
        }
    }
}

and then register It the Global.asax.cs, Application_Start()

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

For formating the textbox while editing using javascript, I added this function:

    function formatWithThousandSeparator(v) {

    $(v).keyup(function (event) {
        if (event.which >= 37 && event.which <= 40) return;
        $(v).val(function (index, value) {
            return value
                // Keep only digits and decimal points:
                .replace(/[^\d.]/g, "")
                // Remove duplicated decimal point, if one exists:
                .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
                // Keep only two digits past the decimal point:
                .replace(/\.(\d{2})\d+/, '.$1')
                // Add thousands separators:
                .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        });
    });
}

and then called it as:

            $("[data-sthousand-separator]").each(function () {

            formatWithThousandSeparator(this);

        });

Note that

  1. data-sthousand-separator is a custom attribute that I added to the inputs that I need them to be formatted.
  2. The call to formatWithThousandSeparator must be added in the document.ready().

Hope it helps anyone there.

Related