'How to get the object instance in IMetadataAware.OnMetadataCreated
I need to use DisplayAttribute to display a different text in a form of the view, depending on some condition. That condition uses other property of the model.
For instance, in this HTML helper:
@Html.LabelFor(m => m.MyProperty)
I need to render a different label depending on the dynamic condition.
Since DisplayAttribute cannot be inheritted, I created a new attribute this way:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = false)]
public sealed class DisplayByTypeAttribute : Attribute, IMetadataAware
{
public string OtherPropertyName { get; set; }
public string NameIfWorker { get; set; }
public string NameIfStudent { get; set; }
public DisplayByTypeAttribute(string otherPropertyName, string nameIfWorker, string nameIfStudent)
{
this.OtherPropertyName = otherPropertyName;
this.NameIfWorker = nameIfWorker;
this.NameIfStudent = nameIfStudent;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
PropertyInfo empresaProp = metadata.ContainerType.GetProperty("EmpresaId");
if (empresaProp == null || metadata.Container == null)
metadata.DisplayName = NameIfWorker ?? string.Empty;
else
{
int empresaId = (int)empresaProp.GetValue(metadata.Container);
if (empresaId > 0)
{
using (Repositories.GestionCasinoCentralEntities db = new Repositories.GestionCasinoCentralEntities())
{
string tipoBeneficiario = db.Empresa.Find(empresaId).EmpresaTipoBeneficiario;
if (tipoBeneficiario == Helpers.TipoBeneficiario.EstudianteCodigo)
metadata.DisplayName = NameIfStudent ?? NameIfWorker ?? string.Empty;
else
metadata.DisplayName = NameIfWorker ?? string.Empty;
}
}
}
}
}
OnMetadataCreated has a parameter that contains 2 interesting properties: Container and ContainerType.
ContainerType has the model type where the property is in, however, Container is null, even when there is an instance of the model.
Is there a way to do what I am trying to do?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
