gpt4 book ai didi

c# - 用逗号 MVC 5 格式化十进制值

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:45 24 4
gpt4 key购买 nike

我有问题!我正在使用 Mvc5,并且我有一个这样的属性。

[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal Total { get; set; }

Razor :

@Html.EditorFor(modelItem => Model.Total, new { htmlAttributes = new { @class = "form-control input-sm" } })

此时没有错误。但是如果我发送 1.300,40,我总是得到 0。

但是如果我发送像 1300,40 这样的值,我会得到正确的值。我该如何解决?我想得到正确的值,如果我发送 1300,50 或 1.300,40

最佳答案

您必须添加自己的ModelBinder:

public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
decimal actualValue = 0;

try
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}

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

并在您的 Application_Start 中注册:

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

引用:http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx/

关于c# - 用逗号 MVC 5 格式化十进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43701083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com