简体   繁体   中英

Modify DataType attribute dynamically in ASP.NET MVC

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:

  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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM