カスタムメタデータプロバイダーを作成し、ShowForEdit
メタデータプロパティを設定できます。したがって、カスタム属性から始めます。
public class ShowForEditAttribute : Attribute
{
public ShowForEditAttribute(bool show)
{
Show = show;
}
public bool Show { get; private set; }
}
次に、カスタムモデルメタデータプロバイダー:
public class MyModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(
IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName
)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
var sfea = attributes.OfType<ShowForEditAttribute>().FirstOrDefault();
if (sfea != null)
{
metadata.ShowForEdit = sfea.Show;
}
return metadata;
}
}
次に、このプロバイダーを次の場所に登録しますApplication_Start
。
ModelMetadataProviders.Current = new MyModelMetadataProvider();
そして最後に飾る:
public class MyViewModel
{
[ShowForEdit(false)]
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
今、あなたの見解であなたが持っているなら:
@model MyViewModel
<h2>Editor</h2>
@Html.EditorForModel()
<h2>Display</h2>
@Html.DisplayForModel()
プロパティはProp1
エディターテンプレートに含まれません。
ShowForDisplay
備考:メタデータプロパティでも同じことができます。