1

我有一個MVC 4項目,我想使用類似於DisplayFromat的功能,但設置DataFormatString是不夠的。我想調用一個函數來格式化字符串。那可能嗎?自定義DisplayFormat超出DataFormatString

我測試了繼承DisplayFormat,但只是讓我設置DataFormatString

我已經看過定製DataAnnotationsModelMetadataProvider,但我看不到如何讓它調用格式化自定義函數。

我的特殊情況是我需要將整數201351格式化爲「w51 2013」​​。我無法想出一個格式化字符串。

回答

0

最簡單的方法是在你的模型暴露出只讀屬性:

public class Model{ 
    public int mydata{get; set;} 
    public string formattedDate{ 
     get{ 
      string formattedval; 
      // format here 
      return formattedval; 
     }; 
    } 
} 
+1

在我們的情況下,由於各種原因,我們寧願使用數據的註釋做格式化。 – 2013-05-13 13:48:11

0

您可以創建自定義ValidationAttribute。以下是我用於驗證某人選擇了下拉值的一些代碼。

using System.ComponentModel.DataAnnotations; 

public sealed class PleaseSelectAttribute : ValidationAttribute 
    { 
     private readonly string _placeholderValue; 

     public override bool IsValid(object value) 
     { 
      var stringValue = value.ToString(); 
      if (stringValue == _placeholderValue || stringValue == "-1") 
      { 
       ErrorMessage = string.Format("The {0} field is required.", _placeholderValue); 
       return false; 
      } 
      return true; 
     } 

     public PleaseSelectAttribute(string placeholderValue) 
     { 
      _placeholderValue = placeholderValue; 
     } 
    } 

然後使用它:

[Required] 
[Display(Name = "Customer")] 
[PleaseSelect("Customer")] 
public int CustomerId { get; set; } 
+0

這不是原始問題的答案 – BrilBroeder 2015-07-15 19:18:38

相關問題