簡體   English   中英

MVC自定義模型屬性到HTML屬性

[英]MVC Custom Model attribute to HTML attribute

我目前(據我所知)正在濫用ValidateAttribute來獲取生成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-value(或data-之后的任何自定義名稱)代替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};
    }
}

我認為此博客為您的問題提供了很好/詳細的答案: 添加html屬性

基本步驟為:

  1. 創建一個自定義屬性(您已經完成),不要從驗證屬性繼承
  2. 根據數據注釋提供程序創建元數據提供程序,該程序還將讀取您的屬性/將其添加到模型的元數據
  3. 為Textbox創建一個模板,或者在視圖本身內查詢Model.Metadata,以獲取您正在使用的自定義屬性及其值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM