扩展MVC C#LabelFor获取所有属性

时间:2013-09-23 21:54:19

标签: c# asp.net-mvc asp.net-mvc-3 data-annotations

我正在尝试整合一个个性化的LabelFor,它接受在数据注释中组装的类的所有属性,并且当属性更改我的Label时。

示例:

[Obrigatorio]
[Display(Name = "Sexo")]
[SexoComTipoPessoa]
[NotMapped]
public int SexoID { get; set; }

这段代码没问题:

[AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class SexoComTipoPessoa : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectInstance.GetType().GetProperty("TipoPessoaID");

        if (property == null)
            return new ValidationResult("Propriedade desconhecida: 'TipoPessoaID'");

        var propertyValue = property.GetValue(validationContext.ObjectInstance, null);

        /* Tipo de pessoa 2 - é pessoa juridicia */
        if (Convert.ToInt32(propertyValue) == 2)
        {
            if (Convert.ToInt32(value) != 3)
                return new ValidationResult("Para o tipo de pessoa 'Juridíca', deve ser selecionado o sexo 'Não aplicavél'!");
        }
        else if (Convert.ToInt32(propertyValue) == 1)
        {
            if (Convert.ToInt32(value) == 3)
                return new ValidationResult("Para o tipo de pessoa 'Física', deve ser selecionado o sexo 'Masculino' ou 'Feminino'!");
        }

        return ValidationResult.Success;
    }
}

此代码不行,当您需要属性[Obrigatorio]时,标签具有属性Display(Name =“”)并添加“*Obrigatório”或[SexoComTipoPessoa]标签具有属性Display(Name =“”) )并添加“* Sexo deve ser compativel com tipo de pessoa”

公共静态类LabelExtensions

{
  public static MvcHtmlString LabelWithTooltip<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
  {
      var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

      string htmlFieldName = ExpressionHelper.GetExpressionText(expression);                    
      string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();

      if (String.IsNullOrEmpty(labelText))
          return MvcHtmlString.Empty;

      var label = new TagBuilder("label");
      label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));

      if (!string.IsNullOrEmpty(metaData.Description))
          label.Attributes.Add("title", metaData.Description);

      label.SetInnerText(labelText);
      return MvcHtmlString.Create(label.ToString());
  }
}

0 个答案:

没有答案