首页 > 解决方案 > 在视图模型中有条件地更改显示名称

问题描述

我是 Razor 和 View Models 的新手,我只想问是否可以在其中显示不同的字符串[Display(Name = "")]

我尝试在 Display 和变量之间添加条件,但它显示错误

也试过这个

public string Color {get;set;}
public String ColorDisplay
        {
            get
            {
                String name = "";
                if (ColorId == 25 || ColorId == 26)
                {
                    name = "Purple";
                }
                else
                {
                    name = "Green";
                }

                return name;
            }
        }

然后在我看来 @Html.LabelFor(m => m.ColorDisplay)

但似乎不起作用,因为它只是显示ColorDisplay

标签: c#htmlrazormodelviewmodel

解决方案


在这个问题中,您可能需要一个自定义属性来根据属性属性中提供的值更改文本。假设您想要这样的自定义属性用法:

[DisplayWhen("ColorId", 25, 26, "Purple", "Green")]
public String Color { get; set; }

并像这样使用 HTML 助手:

@Html.LabelFor(m => m.Color)

然后你应该执行以下步骤:

1)创建从Attribute类继承的自定义属性。

public class DisplayWhenAttribute : Attribute
{
    private string _propertyName;
    private int _condition1;
    private int _condition2;
    private string _trueValue;
    private string _falseValue;

    public string PropertyName 
    {
       get
       {
           return _propertyName;
       }
    }

    public int Condition1
    {
       get
       {
           return _condition1;
       }
    }

    public int Condition2
    {
       get
       {
           return _condition2;
       }
    }

    public string TrueValue
    {
       get
       {
           return _trueValue;
       }
    }

    public string FalseValue
    {
       get
       {
           return _falseValue;
       }
    }

    public DisplayWhenAttribute(string propertyName, int condition1, int condition2, string trueValue, string falseValue)
    {
        _propertyName = propertyName;
        _condition1 = condition1;
        _condition2 = condition2;
        _trueValue = trueValue;
        _falseValue = falseValue;
    }
}

2) 创建自定义元数据提供程序类,检查自定义属性是否存在。

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        var additionalAttribute = attributes.OfType<DisplayWhenAttribute>().FirstOrDefault();

        if (additionalAttribute != null)
        {
            metadata.AdditionalValues.Add("DisplayWhenAttribute", additionalValues);
        }

        return metadata;
    }
}

3) 像这样注册CustomModelMetadataProviderApplication_Start()Global.asax 中的方法中:

protected void Application_Start()
{
    ModelMetadataProviders.Current = new CustomModelMetadataProvider();
}

4)创建您自己的(或覆盖现有的)LabelFor助手,以便它检查DisplayWhenAttribute,如下例所示:

public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
    string result = string.Empty;

    var modelMetaData = expression.Compile().Invoke(helper.ViewData.Model);
    string fieldName = ExpressionHelper.GetExpressionText(expression);

    var containerType = typeof(TModel);
    var containerProperties = containerType.GetProperties();

    var propertyInfo = containerProperties.SingleOrDefault(x => x.Name == modelMetaData.PropertyName);
    var attribute = propertyInfo.GetCustomAttributes(false).SingleOrDefault(x => x is DisplayWhenAttribute) as DisplayWhenAttribute;

    var target = attribute.PropertyName; // target property name, e.g. ColorId
    var condition1 = attribute.Condition1; // first value to check
    var condition2 = attribute.Condition2; // second value to check

    var targetValue = (int)containerType.GetProperty(target).GetValue(helper.ViewData.Model);  

    // checking provided values from attribute
    if (targetValue == condition1 || targetValue == condition2)
    {
        result = attribute.TrueValue;
    }      
    else
    {
        result = attribute.FalseValue;
    }

    // create <label> tag with specified true/false value
    TagBuilder tag = new TagBuilder("label");
    tag.MergeAttributes(htmlAttributes);
    tag.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(fieldName));
    tag.SetInnerText(result);

    return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}

需要考虑的一些参考资料:

是否可以将条件属性创建为 DisplayIf?

如何扩展 MVC3 标签和 LabelFor HTML 助手?

MVC 自定义显示属性


推荐阅读