Reputation: 5637
I'm having trouble when rendering a text box using @Html.TextBoxFor
with a custom type I've created. My custom type looks like this:
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;
}
...
}
Then on my model, I have:
public class ExampleModel
{
public Encrypted<string> Name { get; set; }
}
If I manually populate the value in my controller action:
public ActionResult Index()
{
var model = new ExampleModel
{
Name = "Example Name";
};
return View(model);
}
Then on my view I have the standard @Html.TextBoxFor(m => m.Name)
. However, when that renders, the value of my text box gets set to: Services.Encrypted`1[System.String]`
Presumably this is because I'm using a custom type and the compiler doesn't know how to convert my type to a string value.
I've tried using a custom 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;
}
Then on my Encrypted model I added:
[TypeConverter(typeof(EncryptedTypeConveter))]
However it doesn't seem to be using the custom TypeConverter
. Does anyone know how I can resolve this?
Upvotes: 3
Views: 499