ASP.NET MVC: Why can't I set ShowForEdit model metadata with an attribute?

Why can't I set model metadata ShowForEditwith an attribute?

It seems that the only attribute that can be changed is [ScaffoldColumn]that which sets both ShowForEdit, and ShowForDisplaythat I do not want to do. I want to be able to comment on these two separately from my model.

+3
source share
2 answers

Because it is not supported out of the box. AFAIK, the reason is that the dataannotations attribute, which supports this functionality, is in .net 4.0 and so that compatibility with MVC 3.5 and 4.0 is excluded.

- Edit/Show, /:

EditorForModel DisplayForModel MVC2

+5

, ? Reflector, , ShowForEdit ShowForDisplay :

ShowForEdit: System.Web.Mvc.Html.DefaultEditorTemplates.ShouldShow(...)

ShowForDisplay: System.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), , , EntityState (, ), .IsComplexType.

IsComplexType:

public virtual bool IsComplexType
{
  get
  {
    return !TypeDescriptor.GetConverter(this.ModelType).CanConvertFrom(typeof(string));
  }
}

, , true, , ShouldShow() , , CAN .

, TypeConverter, , :

:

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

, .

+4

Source: https://habr.com/ru/post/1749363/


All Articles