c# - 无效的十进制验证
问题描述
我编写了一个带有模型验证的应用程序,但是当我尝试输入十进制值时,我得到了
值“12.12”对价格无效。
[Required(ErrorMessage = "Price is required.")]
[Range(0, 9999.99)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
解决方案
2年后,我再次偶然发现了这一点。我以为 ASP.NET MVC 5 已经解决了这个问题,但看起来情况并非如此。所以这里是如何解决这个问题的。
创建一个名为 DecimalModelBinder 的类,如下所示,并将其添加到项目的根目录,例如:
using System;
using System.Globalization;
using System.Web.Mvc;
namespace YourNamespace
{
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;
if(valueResult.AttemptedValue != string.Empty)
{
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 DecimalModelBinder());
推荐阅读
- android - 用于 Kotlin 多平台移动设备的 Skia
- r - 在 R 中,如何从列中提取多个变量并创建新变量
- kotlin - 赋值不是表达式,在这个上下文中只允许表达式 Spring Boot Kotllin
- javascript - 如何动态更新html下拉列表值
- postgresql - 在 postgreSQL 中使用空左连接条件更新查询
- angular - Cognito:放大 Angular 中的用户创建
- php - 使用 Wordpress 在菜单中未正确显示短划线图标
- html - 在 Keycloak 的自定义主题中引用字体
- ios - 如何在 UIActivityViewController 中显示带有文本的 URL 图标?
- android - Superpowered SDK:如何在文件上应用音高转换然后将其保存到外部存储?