首页 文章

Typeconverter无法在asp.net核心中运行

提问于
浏览
9

我将 Amount 存储在数据库中 decimal . 我希望用千位分隔符在UI上显示该值 . 我可以在amount属性上添加 [DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)] 属性,这将显示千位分隔符的数字但是当我将值POST回服务器时,由于逗号,MVC模型绑定将不起作用 .

我创建了一个自定义类型转换器,它将 decimal 转换为 string ,然后 string 转换为 decimal

public class NumberConverter : TypeConverter
{
    public override bool CanConvertFrom(
        ITypeDescriptorContext context,
        Type sourceType)
    {
        if (sourceType == typeof(decimal))
        {
            return true;
        }
        return base.CanConvertFrom(context, sourceType);
    }
    public override object ConvertFrom(ITypeDescriptorContext context,
        CultureInfo culture, object value)
    {
        if (value is decimal)
        {
            return string.Format("{0:N2}", value);
        }
        return base.ConvertFrom(context, culture, value);
    }
    public override bool CanConvertTo(ITypeDescriptorContext context,
        Type destinationType)
    {
        if (destinationType == typeof(decimal))
        {
            return true;
        }
        return base.CanConvertTo(context, destinationType);
    }
    public override object ConvertTo(ITypeDescriptorContext context,
        CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(decimal) && value is string)
        {
            return Scrub(value.ToString());
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }

    private decimal Scrub(string modelValue)
    {
        NumberStyles _currencyStyle = NumberStyles.Currency;
        CultureInfo _culture = new CultureInfo("en-US");

        var modelDecimal = 0M;
        decimal.TryParse(
           modelValue,
           _currencyStyle,
           _culture,
           out modelDecimal
       );

        return modelDecimal;
    }
}

然后我将其应用于其中一个模型属性 . 请注意,模型可能具有其他十进制属性,可能不需要此转换 .

public class MyModel
{

    [TypeConverter(typeof(NumberConverter))]
    [Display(Name = "Enter Amount")]
    public decimal Amount { get; set;}

    public string Name { get; set; }
}

Index.cshtml

<form asp-action="submit" asp-controller="home">
    @Html.EditorFor(m => m.Amount)
    <button type="submit" class="btn btn-primary">Save</button>
</form>

但是转换器代码永远不会被触发 . 当我把突破点放在 NumberConverter 时没有突破点击中 . 我需要在任何地方注册类型转换器吗?我使用的是asp.net核心 .

1 回答

  • 3

    根据我的观察 asp.net core 没有考虑 properties 装饰的 properties .

    所以它只支持 TypeConverters 正在装饰实际类型 class declaration .

    Works

    [TypeConverter(typeof(MyModelStringTypeConverter))]
    public class MyModel
    {
    
    }
    

    Doesn't work

    public class OtherModel
    {
        [TypeConverter(typeof(MyModelStringTypeConverter))]
        public MyModel MyModel { get;set; }
    }
    

相关问题