Back to: ASP.NET Core Tutorials For Beginners and Professionals
Displaying and Formatting Attributes in ASP.NET Core MVC
In this article, I will discuss Displaying and Formatting Data Annotation Attributes in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing Blacklist and Whitelist Checks using Data Annotation in ASP.NET Core MVC.
Creating Model:
First, create a class file named Employee.cs, and then copy and paste the following code. This will be our model class, which will hold the employee data we want to display to the user.
namespace DataAnnotationsDemo.Models { public partial class Employee { public int Id { get; set; } public string FullName { get; set; } public string Gender { get; set; } public int? Age { get; set; } public DateTime? HireDate { get; set; } public string EmailAddress { get; set; } public decimal? Salary { get; set; } public string PersonalWebSite { get; set; } public string OptionalField { get; set; } } }
Creating Controller:
Create a controller named EmployeeController and then copy and paste the following code. Here, we have hardcoded the employee details. But in real time, you will get the details from the database.
using DataAnnotationsDemo.Models; using Microsoft.AspNetCore.Mvc; namespace DataAnnotationsDemo.Controllers { public class EmployeeController : Controller { private List<Employee> _employees; public EmployeeController() { _employees = new List<Employee>() { new Employee{ Id=1, FullName="Pranaya Rout", Gender= "Male", Age= 29, HireDate=Convert.ToDateTime("2017-01-02 17:53:46.833"), EmailAddress= "info@dotnettutorials.net", Salary= 55000, PersonalWebSite= "https://dotnettutorials.net/" }, new Employee{ Id=2, FullName="Pranaya Rout", Gender= "Male", Age= 29, HireDate=Convert.ToDateTime("2017-01-02 17:53:46.833"), EmailAddress= "info@dotnettutorials.net", Salary= 55000, PersonalWebSite= "https://dotnettutorials.net/" } }; } public ActionResult Details(int id) { Employee? employee = _employees.FirstOrDefault(x => x.Id == id); return View(employee); } } }
What is DisplayNameFor in ASP.NET Core MVC?
In ASP.NET Core MVC, DisplayNameFor is a method of the HtmlHelper class used in Razor views to display the “friendly” or “display” name for a model property. This display name can be set using your model’s [Display] attribute.
The primary purpose of DisplayNameFor is to offer a way to display names for properties in a strongly typed manner, ensuring that if property names change during refactoring, your views will automatically reflect those changes.
What is DisplayFor in ASP.NET Core MVC?
In ASP.NET Core MVC, DisplayFor is a HtmlHelper class method used within Razor views. It generates a display field for a model property. The display field is read-only and is meant for displaying values, not collecting input.
- It automatically selects the best way to display the property’s value based on its type and annotations.
- It leverages data annotations and templates to determine how the value of a property should be displayed.
Creating Details View:
Add the Details.cshtml view of the Employee Controller and then copy and paste the following code. For the following view, Employee is the model, and then using DisplayNameFor and DisplayFor HTML helper methods, we display the Employee details.
@model DataAnnotationsDemo.Models.Employee @{ ViewBag.Title = "Details"; } <div> <h4>Employee</h4> <hr /> <dl class="row"> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Id) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Id) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.FullName) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.FullName) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Gender) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Gender) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Age) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Age) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.HireDate) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.HireDate) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.EmailAddress) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.EmailAddress) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.Salary) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.Salary) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.PersonalWebSite) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.PersonalWebSite) </dd> </dl> </div>
With the above changes in place, now run the application and visit the Employee/Details/1 URL, and you should see the following page.
Notice that the output is not that pretty. We can control data display in a view using display attributes in the System.ComponentModel.DataAnnotations namespace. So, modify the Employee.cs class file as follows:
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace DataAnnotationsDemo.Models { public partial class Employee { public int Id { get; set; } //If you want "FullName" to be displayed as "Full Name", //use DisplayAttribute or DisplayName attribute. //DisplayName attribute is in System.ComponentModel namespace. //[DisplayAttribute(Name="Full Name")] //[Display(Name = "Full Name")] [DisplayName("Full Name")] public string FullName { get; set; } // If gender is NULL, "Gender not specified" text will be displayed. [DisplayFormat(NullDisplayText = "Gender not specified")] public string? Gender { get; set; } public int? Age { get; set; } //To get only the date part in a datetime data type [DisplayFormat(DataFormatString = "{0:d}")] //[DisplayFormatAttribute(DataFormatString="{0:d}")] //To get time in 24 hour notation //[DisplayFormat(DataFormatString = "{0:dd/MM/yyyyHH:mm:ss}")] //To get time in 12 hour notation with AM PM //[DisplayFormat(DataFormatString = "{0:dd/MM/yyyyhh:mm:sstt}")] //Display only Time Part //[DataType(DataType.Time)] //Display only Date Part [DataType(DataType.Date)] public DateTime? HireDate { get; set; } [DisplayName("Email Address")] // Display mailto hyperlink [DataType(DataType.EmailAddress)] public string EmailAddress { get; set; } //[DataType(DataType.Currency)] //Display currency symbol. [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true)] public decimal? Salary { get; set; } [DisplayName("Personal WebSite")] // Generate a hyperlink [DataType(DataType.Url)] public string PersonalWebSite { get; set; } // If OptionalField is NULL, "N/A" text will be displayed. [DisplayFormat(NullDisplayText = "N/A")] public string OptionalField { get; set; } } }
Modifying the Program Class:
We need to do some settings in the Main method to display the currency symbol specific to the culture. By default, as I am from India, the currency will be Indian Rupee. Instead of the Indian Rupee, we can also set the currency we want to display, like the US Dollar, Great British Pound, etc. To do so, please modify the Main method of the Program class as shown below.
using Microsoft.AspNetCore.Localization; using Microsoft.Extensions.Options; using System.Drawing; using System.Globalization; using System.Text.RegularExpressions; namespace DataAnnotationsDemo { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); //Configuring the Default Currency to be used in our application builder.Services.Configure<RequestLocalizationOptions>(options => { options.DefaultRequestCulture = new RequestCulture("en-IN"); //options.DefaultRequestCulture = new RequestCulture("en-GB"); //options.DefaultRequestCulture = new RequestCulture("en-US"); }); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); //It will automatically set culture information for requests //based on information provided by the client. app.UseRequestLocalization(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); } } }
With the above changes in place, run the application, and you should get the output as expected, as shown in the below image.
What is Display Attribute in ASP.NET Core MVC?
In ASP.NET Core MVC, the [Display] attribute is a data annotation used to specify additional metadata for a model property, especially related to how the property should be displayed in UI elements. It comes from the System.ComponentModel.DataAnnotations namespace. The [Display] attribute provides several properties that can influence how the property is presented or how it behaves in the UI:
Name:
Specifies a friendly display name for a property, which is often more readable than the property’s actual name.
[Display(Name = “Full Name”)]
public string FullName { get; set; }
Prompt:
Provides a placeholder or prompt for input controls. Useful for providing hints or sample values for a field.
[Display(Prompt = “Enter your full name”)]
public string FullName { get; set; }
Order:
Indicates the order in which a field should be displayed relative to other properties.
[Display(Order = 1)]
public string FirstName { get; set; }
[Display(Order = 2)]
public string LastName { get; set; }
ShortName:
Specifies a shorter version of the display name.
[Display(ShortName = “DOB”)]
public DateTime DateOfBirth { get; set; }
When the model is rendered in a view using the built-in HTML helpers (like @Html.LabelFor(), @Html.EditorFor(), and @Html.DisplayFor()) or the tag helpers in ASP.NET Core, the metadata provided by the [Display] attribute is used to influence the generated output.
It’s worth noting that while the [Display] attribute provides metadata related to the display and behavior of model properties in the UI, it doesn’t enforce any validation rules. For validation, you need to use other attributes, like [Required], [StringLength], [Range], etc.
So, the [Display] attribute in ASP.NET Core MVC allows developers to specify and control various display characteristics of model properties when rendered in views.
What is DisplayFormat Attribute in ASP.NET Core MVC?
In ASP.NET Core MVC, the [DisplayFormat] attribute is a data annotation that provides additional metadata about how a model property should be displayed and formatted. This attribute is part of the System.ComponentModel.DataAnnotations namespace.
The [DisplayFormat] attribute is particularly useful when controlling data formatting for display purposes or accepting user input. Here are the key properties of this attribute:
DataFormatString:
Specifies the display format of the data. This is useful for formatting data types like DateTime, Decimal, etc.
[DisplayFormat(DataFormatString = “{0:yyyy-MM-dd}”)]
public DateTime BirthDate { get; set; }
[DisplayFormat(DataFormatString = “{0:C2}”)]
public decimal Price { get; set; }
ApplyFormatInEditMode:
When set to true, the format specified in DataFormatString will also be applied when the property is in edit mode, not just display mode.
[DisplayFormat(DataFormatString = “{0:yyyy-MM-dd}”, ApplyFormatInEditMode = true)]
public DateTime BirthDate { get; set; }
NullDisplayText:
Specifies a text to display when the value of the property is null.
[DisplayFormat(NullDisplayText = “N/A”)]
public string OptionalField { get; set; }
ConvertEmptyStringToNull:
When set to true (the default), if an empty string is assigned to the property, it will be converted to null. This can be especially useful when dealing with form submissions where empty input fields translate to empty strings by default.
[DisplayFormat(ConvertEmptyStringToNull = true)]
public string Name { get; set; }
When using MVC’s built-in HTML helpers, like @Html.DisplayFor() or @Html.EditorFor(), the [DisplayFormat] attribute will influence how the property is rendered:
- DisplayFor will use the format specified in DataFormatString when displaying the property’s value.
- If ApplyFormatInEditMode is true, EditorFor will also use the format specified in DataFormatString when rendering the input field for editing.
So, the [DisplayFormat] attribute in ASP.NET Core MVC allows developers to control the display and format of model properties, ensuring that data is presented consistently and accurately in views.
In the next article, I will discuss Multiple Real-Time Examples of Data Annotations in ASP.NET Core MVC. In this article, I try to explain Displaying and Formatting Data Annotation Attributes in ASP.NET Core MVC Application with examples. I hope you enjoy this Displaying and Formatting Data Annotation Attributes in the ASP.NET Core MVC article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.