1
votes

Is there a way that I can add non-static data to dataannotation attributes (either the standard attributes or a custom attribute that inherits from either a standard dataannotation (display, range, etc.) or the attribute base class)? I'm hoping to do something like this:

public class ReportingDateTime
{
    [Display(Name=this.FieldName)]
    [Reporting.Core.CustomDisplay(this.FieldName)]

    public DateTime Field { get; set; }

    private string FieldName;

    public ReportingDateTime(string fieldName)
    {
        this.FieldName = fieldName;
    }
}

Alternatively, is there a way to change the metadata for a property in the class' constructor like so:

public class ReportingDateTime
{
    public DateTime Field { get; set; }

    private string FieldName;

    public ReportingDateTime(string fieldName)
    {
        Field.metadata.DisplayName = "Test Date";
    }
}

From what I've seen there has been some success passing the type of an object (the custom attribute expected a new instance of a custom object) but I'm primarily looking at simple data types (string, int, double) and perhaps generic collections (list, dictionary, etc.)

1

1 Answers

0
votes

As far as I can tell there is no way to currently do this. What ended up working for me was to have custom editor/display templates for that class so I could use my own fields for the display property, like so:

@inherits System.Web.Mvc.WebViewPage<Reporting.Fields.ReportingNumber>
<div class="editor-label">
    @Model.FieldName
</div>
<div class="editor-field">
    @if (Model.ReadOnly)
    {
        <div class="@Model.FieldSubType">
            @Model.Field
        </div>
    }
    else
    {
        @Html.TextBox("Field", Model.Field, new { @class = @Model.FieldSubType, @title = @Model.ToolTip })
        @Html.ValidationMessageFor(model => model.Field)
    }

For validation I'd recommend using FluentValidation's conditional validation (http://fluentvalidation.codeplex.com/wikipage?title=Customising&referringTitle=Documentation&ANCHOR#WhenUnless) and use the properties in your class as the conditional statements.

namespace Reporting.Validation
{
    using FluentValidation;
    using Reporting.Fields;

    public class ReportingNumberValidation : AbstractValidator<ReportingNumber>
    {
        public ReportingNumberValidation()
        {
            RuleFor(m => m.Field).NotEmpty().WithMessage("*").When(m => m.Required);
            RuleFor(m => m.Field).GreaterThanOrEqualTo(m => m.MinimumValue.Value).When(m => m.MinimumValue.HasValue);
            RuleFor(m => m.Field).LessThanOrEqualTo(m => m.MaximumValue.Value).When(m => m.MaximumValue.HasValue);
        }
    }
}