要在ASP.NET Core应用程序中使用点替换逗号,可以使用IModelBinder或ValidationAttribute。以下是使用ValidationAttribute实现此目标的示例:
using System.ComponentModel.DataAnnotations;
public class ReplaceCommaAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null) { return ValidationResult.Success; }
var stringValue = value.ToString();
var decimalSeparator = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
if (stringValue.Contains(","))
{
stringValue = stringValue.Replace(",", decimalSeparator);
decimal parsedValue;
if (!decimal.TryParse(stringValue, out parsedValue))
{
return new ValidationResult($"The value {value} is invalid.");
}
value = parsedValue;
}
return ValidationResult.Success;
}
}
public class MyModel { [ReplaceComma] public decimal MyProperty { get; set; } }
现在,当用户在表单中输入带有逗号的货币值时,MyProperty属性中的值将包含点而不是逗号。