这似乎类似问题Why can't I set ShowForEdit model metadata with an attribute?,所以我会在这里复制我的答案:
什么是你申请它属性的类型?如果我们使用反射,我们可以发现,ShowForEdit和ShowForDisplay属性在以下功能使用:
ShowForEdit:System.Web.Mvc.Html.DefaultEditorTemplates.ShouldShow(...)
ShowForDisplay:系统.Web.Mvc.Html.DefaultDisplayTemplates.ShouldShow(...)
这些方法的定义是:
private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
{
return (((metadata.ShowForEdit && (metadata.ModelType != typeof(EntityState))) && !metadata.IsComplexType) && !templateInfo.Visited(metadata));
}
private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)
{
return (((metadata.ShowForDisplay && (metadata.ModelType != typeof(EntityState))) && !metadata.IsComplexType) && !templateInfo.Visited(metadata));
}
无视明显的性能检查(metadata.ShowForX),你可以看到,它是检查模型是否是a n EntityState的实体(可能不是),然后检查metadata.IsComplexType。
我们可以看看IsComplexType物业位置:
public virtual bool IsComplexType
{
get
{
return !TypeDescriptor.GetConverter(this.ModelType).CanConvertFrom(typeof(string));
}
}
那是什么要说的是,它会返回true,如果模型无法从字符串转换,并在ShouldShow()方法,它会显示它是不是一个复杂的类型,即值可以从一个字符串转换。
,你需要做的,是创建一个类型转换器,可以转换为字符串,该模型,如:
模型:
[TypeConverter(typeof(ItemConverter))]
public class Item
{
#region Properties
public string Text { get; set; }
#endregion
}
和转换器:
public class ItemConverter : TypeConverter
{
#region Methods
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value.GetType() == typeof(string))
{
return new Item { Text = (string)value };
}
return base.ConvertFrom(context, culture, value);
}
#endregion
}
随着这一点,再试一次,看看是否有帮助。