自定义类型转换字符串
本文关键字:字符串 类型转换 自定义 | 更新日期: 2023-09-27 18:34:11
使用具有我创建的自定义类型的@Html.TextBoxFor
渲染文本框时遇到问题。我的自定义类型如下所示:
public class Encrypted<T>
{
private readonly Lazy<T> _decrypted;
private readonly Lazy<string> _encrypted;
public static implicit operator Encrypted<T>(T value)
{
return new Encrypted<T>(value);
}
public static implicit operator string(Encrypted<T> value)
{
return value._encrypted.Value;
}
...
}
然后在我的模型上,我有:
public class ExampleModel
{
public Encrypted<string> Name { get; set; }
}
如果我在控制器操作中手动填充值:
public ActionResult Index()
{
var model = new ExampleModel
{
Name = "Example Name";
};
return View(model);
}
然后在我看来,我有标准@Html.TextBoxFor(m => m.Name)
.但是,当呈现时,我的文本框的值设置为:服务.加密'1[系统.字符串]'
大概这是因为我使用的是自定义类型,而编译器不知道如何将我的类型转换为字符串值。
我尝试使用自定义TypeConverter
:
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
var encrypted = value as IEncrypted;
if (encrypted != null)
{
return encrypted.DecryptedValue();
}
}
return null;
}
然后在我的加密模型上,我添加了:
[TypeConverter(typeof(EncryptedTypeConveter))]
但是,它似乎没有使用自定义TypeConverter
。有谁知道我该如何解决这个问题?
您需要
覆盖ToString()
。