首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MVC 5 Razor数字格式

MVC 5 Razor数字格式
EN

Stack Overflow用户
提问于 2022-09-12 17:24:05
回答 1查看 24关注 0票数 0
代码语言:javascript
复制
    [DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
    public decimal AmpereFee {
        get {
            return this._ampereFee;
        }
        set {
            this._ampereFee = value;
        }
    }

在视野中

代码语言:javascript
复制
       @Html.EditorFor(model => model.AmpereFee, new { htmlAttributes = new { @class = "form-control" } })

当我第一次加载页面时,会完美地显示数字:

我有两个问题:第一个问题,当我单击submit时,我有以下错误:

第二个错误是,当我编辑数字时,它没有正确显示,如下面的图像所示。

这两个问题的解决办法是什么?

EN

回答 1

Stack Overflow用户

发布于 2022-09-13 09:17:09

经过几个小时的搜索,我找到了答案:

  1. 用于停止错误,我们需要创建一个自定义模型绑定器,因此创建这个类:

使用系统;

使用System.Web.Mvc;

代码语言:javascript
复制
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;
        }
    }
}

然后将其注册为Global.asax.cs,Application_Start()

代码语言:javascript
复制
    ModelBinders.Binders.Add(typeof(decimal), new SDecimalModelBinder());

为了在使用javascript编辑时形成textbox,我添加了以下函数:

代码语言:javascript
复制
    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, ",")
        });
    });
}

然后称之为:

代码语言:javascript
复制
            $("[data-sthousand-separator]").each(function () {

            formatWithThousandSeparator(this);

        });

注意到

  1. data-sthousand-separator是一个自定义属性,我将其添加到需要它们的输入中,formatted.
  2. The调用formatWithThousandSeparator必须添加到document.ready().

中。

希望它能帮助到那里的任何人。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73693024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档