gpt4 book ai didi

asp.net-core - 类型转换器在 asp.net 核心中不起作用

转载 作者:行者123 更新时间:2023-12-03 17:36:44 25 4
gpt4 key购买 nike

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

我创建了一个自定义类型转换器,可以从 decimal 转换至string然后 stringdecimal

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; }
}

索引.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 核心。

最佳答案

根据我的观察 asp.net core不考虑房产 TypeConverters 装饰.

所以只支持TypeConverters正在装饰实际类型类声明 .

作品

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

}

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

关于asp.net-core - 类型转换器在 asp.net 核心中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43378709/

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