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.
You can customize the display template of EmailAddress
. To do so:
DisplayTemplates
folder under Views/Shared
EmailAddress.cshtml
file in DisplayTemplates
folderAdd 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.