asp.net-mvcrazorenginemodelmetadata

Getting the attributes of the field in additional EditorTemplate


I want to make additional editor template for the Int32. In it I want to get all attributes(custom/default-data-annotations) and do some work with them:

@model Int32

@{
    string propertyName = ViewData.ModelMetadata.PropertyName;
    var attributes = ViewData.ModelMetadata.GetSomeHowAllTheAttributesOfTheProperty;
    SomeWorkWithAttribute(attributes);

}
<input type="text" name="@propertyName" value="@ViewData.ModelMetadata.DisplayFormatString" class="form-control"/>

So the question how to get in the EditorTemplate all attributes of the property?

Thx in advance


Solution

  • EDIT: initial answer removed (not enough info in the question):

    Since you need to access your custom attribute, I suggest the following:

    A: if you're just saving some values using your custom attribute, use the AdditionalMetadataAttribute:

    Model:

    [Additional("myAdditionalInfoField", "myAdditionalInfoValue")]
    public int IntProperty { get; set; }
    

    View:

    @{
        string valueFromAttribute = ViewData.ModelMetadata.Additional["myAdditionalInfoField"].ToString();
    }
    

    B: if you're doing more complex work inside your custom attribute, get the current metadata property for your model and save the computed values inside the ViewData.ModelMetadata.Additional dictionary. Please note that this requires that you implement your custom metadata provider. A detailed implementation can be found here.