Getting the attributes of the field in additional EditorTemplate

2.7k views Asked by At

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

2

There are 2 answers

8
Andrei V On BEST ANSWER

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.

0
Muhammad Assar On

this is how to access all the attributes in your model property from the DisplayTemplate or EditorTemplate:

var attributes = ((Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadata)ViewData.ModelMetadata).Attributes;

then you can get the desired custom attribute:

var yourAttribute = attributes.PropertyAttributes.OfType<YourAttribute>().FirstOrDefault();

now you have yourAttribute to do what ever you want!