[DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
public decimal AmpereFee {
get {
return this._ampereFee;
}
set {
this._ampereFee = value;
}
}在视野中
@Html.EditorFor(model => model.AmpereFee, new { htmlAttributes = new { @class = "form-control" } })当我第一次加载页面时,会完美地显示数字:

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

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

这两个问题的解决办法是什么?
发布于 2022-09-13 09:17:09
经过几个小时的搜索,我找到了答案:
使用系统;
使用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;
}
}
}然后将其注册为Global.asax.cs,Application_Start()
ModelBinders.Binders.Add(typeof(decimal), new SDecimalModelBinder());为了在使用javascript编辑时形成textbox,我添加了以下函数:
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, ",")
});
});
}然后称之为:
$("[data-sthousand-separator]").each(function () {
formatWithThousandSeparator(this);
});注意到
中。
希望它能帮助到那里的任何人。
https://stackoverflow.com/questions/73693024
复制相似问题