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