【问题标题】:MVC Custom Model attribute to HTML attributeMVC 自定义模型属性到 HTML 属性
【发布时间】:2012-05-15 02:37:58
【问题描述】:

我目前(据我所知)滥用 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};
    }
}

【问题讨论】:

    标签: c# model-view-controller attributes adapter


    【解决方案1】:

    我认为这个博客包含一个非常好的/详细的回答你的问题: add html attributes

    基本步骤是:

    1. 创建自定义属性(您已经完成),不要从验证属性继承
    2. 基于数据注释提供者创建一个元数据提供者,它还将读取/添加您的属性到模型的元数据中
    3. 为文本框创建模板,或在视图本身中查询 Model.Metadata,以获取您正在使用的自定义属性及其值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多