1

I have a ViewModel containing this property:

[Display(Name = "Email")]        
[DataType(DataType.EmailAddress)]        
[DisplayFormat(NullDisplayText = "Unavailable")]        
public string Email { get; set; }

Is there a way to set the DataType attribute dynamically to show it as a DataType.Text if it's showing "Unavailable" (the NullDisplayText), otherwise show it as a clickable DataType.EmailAddress?

Now, when the property value is null, it shows like Unavailable while I want to show it as Unavailable.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Wadjey
  • 145
  • 13

1 Answers1

1

You can customize the display template of EmailAddress. To do so:

  1. Create a DisplayTemplates folder under Views/Shared
  2. Create an EmailAddress.cshtml file in DisplayTemplates folder
  3. Add the following content to the file and save it:

    @model string
    @if (string.IsNullOrEmpty(Model))
    {
        @ViewData.TemplateInfo.FormattedModelValue
    }
    else
    {
        <a href="mailto:@Model">@ViewData.TemplateInfo.FormattedModelValue</a>
    }
    

Since now, when you use a [DataType(DataType.EmailAddress)] attribute for a property, your EmailAddress display template will be used.

You can put any logic inside it to do a custom render.

Note: If you want to limit the template to your specific views, let's say just for MyModel views, then create the EmailAddress template in Views\MyModel\DisplayTemplates.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • DisplayTemplates and EditorTemplates are one of the most useful extension points in the framework for Views. Let me know if you have any problem in applying the solution :) – Reza Aghaei Feb 06 '20 at 14:27