2011-11-23 81 views
1

我目前正在濫用(據我所知)一個ValidateAttribute獲取生成HTML視圖時顯示的模型屬性。MVC自定義模型屬性爲HTML屬性

我有一個模型屬性,具有自定義屬性(使一些客戶方JSON處理):這是在視圖中使用這樣的

[JsonResultPair("Zipcode","City")] 
public virtual string City { get; set; } 

@Html.TextBoxFor(m => m.City, new { @class = "A", tabindex = 10, title = "B" }) 

導致:

<input class="A" data-val="true" data-val-pair="" data-val-pair-fld="City" data-val-pair-src="Zipcode" id="City" name="City" tabindex="10" title="B" type="text" value=""/> 

但理想情況下,我想省略data-val-pair =「」屬性,通常用於保存錯誤消息,因爲這不是實際的驗證。我想使用數據值(或數據後的任何自定義名稱)而不是data-val。任何想法如何做到這一點?

我當前屬性的實現:

[AttributeUsage(AttributeTargets.Property)] 
public class JsonResultPair: ValidationAttribute 
{ 
    private readonly String _source; 
    private readonly String _field; 

    public JsonResultPair(String source, String field) 
    { 
     _source = source; 
     _field = field; 
    } 

    public String Source { get { return _source; } } 
    public String Field { get { return _field; } } 
} 

我目前適配器實現:

// thanks: http://stackoverflow.com/questions/4120792/how-can-i-have-a-custom-validationattribute-rendered-as-a-data-val-xx-attribut 
public class JsonResultPairAdapter : DataAnnotationsModelValidator<JsonResultPair> 
{ 
    private const String Pair = "pair"; 
    private const String PairSource = "src"; 
    private const String PairField = "fld"; 

    public JsonResultPairAdapter(ModelMetadata metadata, ControllerContext context, JsonResultPair attribute) : base(metadata, context, attribute) 
    { 
    } 

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() 
    { 
     ModelClientValidationRule rule = new ModelClientValidationRule 
     { 
      ErrorMessage = ErrorMessage, 
      ValidationType = Pair 
     }; 

     rule.ValidationParameters.Add(PairSource, Attribute.Source); 
     rule.ValidationParameters.Add(PairField, Attribute.Field); 

     return new []{ rule}; 
    } 
} 

回答

1

我覺得這個博客包含了你的問題非常好/詳細的解答: add html attributes

基本步驟如下:

  1. 創建一個自定義屬性(你已經做了),沒有從驗證繼承屬性
  2. 創建元數據提供商,基於數據的註釋供應商,這也將讀/添加屬性模型的元數據
  3. 要麼爲文本框創建模板,要麼在視圖本身內創建查詢Model.Metadata,以獲取您正在使用的自定義屬性及其值。