From 5ae67de74c687907a745532d48ac66c7f5fec05b Mon Sep 17 00:00:00 2001 From: capdiem Date: Tue, 26 Nov 2024 14:15:01 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(TextField):=20handle=20case?= =?UTF-8?q?=20when=20Type=20is=20'number'=20and=20Value=20is=20type=20of?= =?UTF-8?q?=20string=20(#2264)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Components/TextField/MTextField.razor.cs | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/Masa.Blazor/Components/TextField/MTextField.razor.cs b/src/Masa.Blazor/Components/TextField/MTextField.razor.cs index cca4f954eb..3d7e8a53e5 100644 --- a/src/Masa.Blazor/Components/TextField/MTextField.razor.cs +++ b/src/Masa.Blazor/Components/TextField/MTextField.razor.cs @@ -545,20 +545,32 @@ protected override void UpdateInternalValue(TValue? value, InternalValueChangeTy { base.UpdateInternalValue(value, changeType); - if (IsNumberType && value is IConvertible convertible) + if (IsNumeric(value, out var numeric)) { - var decimalValue = Convert.ToDecimal(convertible, CultureInfo.InvariantCulture); + var decimalValue = Convert.ToDecimal(numeric, CultureInfo.InvariantCulture); UpButtonEnabled = !Props.Max.HasValue || decimalValue < Props.Max; DownButtonEnabled = !Props.Min.HasValue || decimalValue > Props.Min; } } + private bool IsNumeric(TValue? value, out IConvertible numeric) + { + numeric = default; + if (IsNumberType && value is not string && value is IConvertible convertible) + { + numeric = convertible; + return true; + } + + return false; + } + protected override TValue? ConvertAndSetValueByJSInterop(TValue? val) { - if (IsNumberType && Props.Precision.HasValue && val is IConvertible convertible) + if (Props.Precision.HasValue && IsNumeric(val, out var numeric)) { - var decimalValue = Convert.ToDecimal(convertible, CultureInfo.InvariantCulture); + var decimalValue = Convert.ToDecimal(numeric, CultureInfo.InvariantCulture); var newValue = Math.Round(decimalValue, Props.Precision.Value); _ = SetValueByJsInterop(newValue.ToString(Props.PrecisionFormat, CultureInfo.InvariantCulture)); return (TValue)Convert.ChangeType(newValue, typeof(TValue), CultureInfo.InvariantCulture); @@ -611,9 +623,9 @@ private void UpdateValue(string? originValue, bool succeeded, TValue? convertedV private TValue GetValidValue(TValue val) { - if (IsNumberType && val is IConvertible convertible) + if (IsNumeric(val, out var numeric)) { - var decimalValue = Convert.ToDecimal(convertible, CultureInfo.InvariantCulture); + var decimalValue = Convert.ToDecimal(numeric, CultureInfo.InvariantCulture); if (Props.Min.HasValue && decimalValue < Props.Min) {