1

有沒有一種方法可以將非靜態數據添加到數據註解屬性(標準屬性或從標準數據註釋(顯示,範圍等)或屬性基類)?我希望做這樣的事情:如何在數據註解中使用變量或類屬性

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; 
    } 
} 

或者,有沒有辦法來更改元數據在類屬性的構造函數,像這樣:

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

    private string FieldName; 

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

從我看到已經有一些成功傳遞一個對象的類型(自定義屬性期望自定義對象的一個​​新實例),但我主要看簡單的數據類型(字符串,int,雙),也許泛型集合(列表,字典,等)

回答

0

據我所知,沒有辦法cu正好這樣做。什麼結束了,我的工作是有自定義編輯器/顯示模板爲類,所以我可以用我自己的字段顯示屬性,像這樣:

@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) 
    } 

爲了驗證我推薦使用FluentValidation的條件驗證( http://fluentvalidation.codeplex.com/wikipage?title=Customising&referringTitle=Documentation&ANCHOR#WhenUnless),並使用你的類中的屬性作爲條件語句。

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); 
     } 
    } 
} 
相關問題