1

Im new to Razor and View Models and I just want to ask if its possible to Display different string in [Display(Name = "")]

I tried adding condition in between the Display and the variable but it shows error

also tried this

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

                return name;
            }
        }

Then in my View @Html.LabelFor(m => m.ColorDisplay)

but seems not working as it just dispay ColorDisplay

Enrique Gil
  • 754
  • 4
  • 19
  • 50
  • Is that `ColorId` an int property? Sounds like you can create custom attribute like `[DisplayWhen("ColorId", 25, 26, "Purple", "Green")]`. – Tetsuya Yamamoto Oct 12 '18 at 08:36
  • @TetsuyaYamamoto is the colorid 25 or 26 still works like the one you provided? yes colorId is in `int` – Enrique Gil Oct 12 '18 at 08:43
  • Note that's custom attribute I proposed, the default `DisplayAttribute` doesn't have parameters like that. What I want to know first is `ColorId` definition as a property which is part of the model class or a local variable/field. – Tetsuya Yamamoto Oct 12 '18 at 08:46
  • @TetsuyaYamamoto yes it is included on my current viewmodel as `int ColorId` – Enrique Gil Oct 12 '18 at 08:48

1 Answers1

1

In this issue, probably you may need a custom attribute to change text based on provided values inside attribute properties. Assumed that you want custom attribute usage like this:

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

And using HTML helper like this:

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

Then you should do these steps:

1) Create a custom attribute inherited from Attribute class.

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) Create custom metadata provider class which checks existence of custom attribute.

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) Register CustomModelMetadataProvider into Application_Start() method inside Global.asax like this:

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

4) Create your own (or override existing) LabelFor helper so that it checks against DisplayWhenAttribute, as in example below:

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

Some references to consider with:

Is it possible to create conditional attribute as DisplayIf?

How to extend MVC3 Label and LabelFor HTML helpers?

MVC custom display attribute

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61