在视图模型中有条件地更改显示名称

时间:2018-10-12 08:27:52

标签: c# html5 razor model viewmodel

我是Razor和View模型的新手,我只想问一下是否有可能在[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

1 个答案:

答案 0 :(得分:0)

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

[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)像这样将CustomModelMetadataProvider注册到Global.asax中的Application_Start()方法中:

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

要考虑的一些参考文献:

Is it possible to create conditional attribute as DisplayIf?

How to extend MVC3 Label and LabelFor HTML helpers?

MVC custom display attribute