Display and DisplayFormat Attributes in ASP.NET Core MVC

Display and DisplayFormat Attributes in ASP.NET Core MVC

In this article, I will discuss Display and DisplayFormat Data Annotation Attributes in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing Remote Validation in ASP.NET Core MVC Applications. We are provided with Display, DisplayName, and DisplayFormat Attributes for displaying and formatting purposes, which we can apply to the Model properties. To take this effect, we need to use DisplayFor and DisplayNameFor HTML Helper methods on views.

DisplayFor and DisplayNameFor Helper Methods in ASP.NET Core MVC

In ASP.NET Core MVC, the DisplayFor and DisplayNameFor HTML helper methods play an important role in displaying model properties in a view. They help render data while respecting the data annotations applied to model properties. In this article, I will discuss how to use these helper methods effectively and demonstrate their behavior with and without Display and DisplayFormat attributes in the ASP.NET Core MVC Application.

DisplayNameFor HTML Helper Method:

The DisplayNameFor helper method displays the name (label) of a model property. This is useful for labeling fields in views, ensuring that labels are consistent with model metadata. If the property has a Display or DisplayName attribute, it will use the value provided by the attribute as the field label. The Display and DisplayName attributes specify custom labels for the properties. For a better understanding, please have a look at the following model.

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace DisplayFormatDemo.Models
{
    public class Employee
    {
        // Using Display attribute to set a custom label
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        // Using DisplayName attribute to set a custom label
        [DisplayName("Email Address")]
        public string Email { get; set; }

        [Display(Name = "Date of Birth")]
        public DateTime DateOfBirth { get; set; }
    }
}
Explanation:
  • [Display(Name = “First Name”)]: This specifies that the FirstName property should be labeled as “First Name” in the UI. That means that when we use @Html.DisplayNameFor(model => model.FirstName) in a view, it will render “First Name” instead of “FirstName.”
  • [DisplayName(“Email Address”)]: Similar to [Display], it sets the display name for the Email property.
  • [Display(Name = “Date of Birth”)]: Sets a user-friendly name for the DateOfBirth property.
DisplayFor HTML Helper Method

The DisplayFor helper method displays the value of a model property while applying any formatting rules provided by the DisplayFormat attribute or display templates. It’s often used when applying formatting like currency, date, or number formats. The DisplayFormat attribute formats the output of the properties when using @Html.DisplayFor. For a better understanding, please have a look at the following model.

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace DisplayFormatDemo.Models
{
    public class Employee
    {
        // Formats the Salary as currency
        [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true)]
        public decimal Salary { get; set; }

        // Formats the PerformanceRating with two decimal places
        [DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
        public double PerformanceRating { get; set; }

        // Formats the DateOfBirth as "Year-Month-Day"
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime DateOfBirth { get; set; }

        // Displays a default message if JobDescription is null or empty
        [DisplayFormat(NullDisplayText = "No Description Available.")]
        public string JobDescription { get; set; }
    }
}
Explanation:
  • [DisplayFormat(DataFormatString = “{0:C}”, ApplyFormatInEditMode = true)]: Formats the Salary property as currency (e.g., “$10,000.00”). The ApplyFormatInEditMode ensures that the format is applied even when editing the value.
  • [DisplayFormat(DataFormatString = “{0:N2}”, ApplyFormatInEditMode = true)]: Formats the PerformanceRating to two decimal places (e.g., “85.75”).
  • [DisplayFormat(DataFormatString = “{0:yyyy-MM-dd}”, ApplyFormatInEditMode = true)]: Formats the DateOfBirth as “yyyy-MM-dd” (e.g., “1990-05-21”).
  • [DisplayFormat(NullDisplayText = “No Description Available.”)]: If JobDescription is null or empty, it displays “No Description Available.” instead of leaving it blank.
Example to Understand DisplayFor and DisplayNameFor in ASP.NET Core MVC:

Let’s build a simple application to understand how DisplayFor and DisplayNameFor work with the Display and DisplayFormat attributes. First, create a new ASP.NET Core MVC Application named DisplayFormatDemo.

Creating Employee Model:

Next, create a class file named Employee.cs within the Models folder and copy and paste the following code. This will be our model, which will hold the employee data we want to display to the user. Since this model lacks any data annotations, default property names and formats will be used in the UI.

namespace DisplayFormatDemo.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Gender { get; set; }
        public int Age { get; set; }
        public DateTime DateOfJoining { get; set; }
        public string EmailAddress { get; set; }
        public decimal Salary { get; set; }
        public string? PersonalWebsite { get; set; }
        public double PerformanceRating { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string? JobDescription { get; set; }
        public DateTime? LastDateOfWorking { get; set; }
    }
}
Creating Employee Controller:

Create an MVC Empty controller named EmployeeController within the Controllers folder and 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. The Details action creates an instance of Employee with hardcoded data and passes it to the view.

using DisplayFormatDemo.Models;
using Microsoft.AspNetCore.Mvc;

namespace DisplayFormatDemo.Controllers
{
    public class EmployeeController : Controller
    {
        public IActionResult Details()
        {
            // Hardcoded employee details for demonstration
            var employee = new Employee
            {
                Id = 1,
                FullName = "Pranaya Rout",
                Gender = "Male",
                Age = 34,
                DateOfJoining = new DateTime(2017, 1, 2),
                DateOfBirth = new DateTime(1988, 2, 29),
                EmailAddress = "pranaya.rout@example.com",
                Salary = 55000m,
                PersonalWebsite = "https://pranayarout.com",
                PerformanceRating = 4.5567,
                JobDescription = string.Empty,
                LastDateOfWorking = null
            };
            return View(employee);
        }
    }
}
Creating Details View:

Add a view named Details.cshtml within the Views/Employee folder and copy and paste the following code. For the following view, the Employee is the model. Using DisplayNameFor, we display the label text of the property, i.e., the property name, and using DisplayFor, we display the values of the properties.

@model DisplayFormatDemo.Models.Employee

@{
    ViewData["Title"] = "Employee Details";
}

<div class="container mt-4">
    <h2>@ViewData["Title"]</h2>
  
    <table class="table table-bordered">
        <tbody>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.Id)</th>
                <td>@Html.DisplayFor(model => model.Id)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.FullName)</th>
                <td>@Html.DisplayFor(model => model.FullName)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.Gender)</th>
                <td>@Html.DisplayFor(model => model.Gender)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.Age)</th>
                <td>@Html.DisplayFor(model => model.Age)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.DateOfJoining)</th>
                <td>@Html.DisplayFor(model => model.DateOfJoining)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.LastDateOfWorking)</th>
                <td>@Html.DisplayFor(model => model.LastDateOfWorking)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.EmailAddress)</th>
                <td>@Html.DisplayFor(model => model.EmailAddress)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.Salary)</th>
                <td>@Html.DisplayFor(model => model.Salary)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.PersonalWebsite)</th>
                <td>@Html.DisplayFor(model => model.PersonalWebsite)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.PerformanceRating)</th>
                <td>@Html.DisplayFor(model => model.PerformanceRating)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.DateOfBirth)</th>
                <td>@Html.DisplayFor(model => model.DateOfBirth)</td>
            </tr>
            <tr>
                <th scope="row">@Html.DisplayNameFor(model => model.JobDescription)</th>
                <td>@Html.DisplayFor(model => model.JobDescription)</td>
            </tr>
        </tbody>
    </table>
</div>

Run the application and navigate to Employee/Details. You should see a neatly formatted list of employee details. However, without any data annotations, the labels are directly derived from the property names, and values are displayed in their default formats, as shown in the image below.

Display and DisplayFormat Attributes in ASP.NET Core MVC

Observations:
  • Labels like “FullName” and “EmailAddress” are directly taken from property names, which may not be user-friendly.
  • Dates and numbers are displayed in default formats, which might not align with user expectations or regional settings.
  • Null or empty values (e.g., LastDateOfWorking, JobDescription) are displayed as blank, which might be confusing.
Enhancing the Example with Display and DisplayFormat Attributes:

We can apply Display and DisplayFormat attributes to the model properties to improve the user interface and data presentation. This allows label customization, values formatting, and handling null or empty fields. So, modify the Employee.cs class file as follows:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace DisplayFormatDemo.Models
{
    public class Employee
    {
        public int Id { get; set; }

        // Applying Display attribute to change the label as Full Name

        [Display(Name = "Full Name")]
        public string FullName { get; set; }

        // Display "Gender Not Specified" if the value is null

        [DisplayFormat(NullDisplayText = "Gender Not Specified")]
        public string Gender { get; set; }

        public int Age { get; set; }

        // Format the date as "dd/MM/yyyy"
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        // Applying Display attribute to change the label as Date of Joining
        [Display(Name = "Date of Joining")]
        public DateTime DateOfJoining { get; set; }

        // Change the display name and specify email data type
        [Display(Name = "Email Address")]
        [DataType(DataType.EmailAddress)]
        public string EmailAddress { get; set; }

        // Formats Salary as currency
        [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true)]
        public decimal Salary { get; set; }

        // Change the display name and specify URL data type
        [Display(Name = "Personal Website")]
        [DataType(DataType.Url)]
        public string? PersonalWebsite { get; set; }

        // Formats PerformanceRating to two decimal places
        [DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
        // Applying Display attribute to change the label as Personal Website
        [Display(Name = "Personal Website")]
        public double PerformanceRating { get; set; }

        // Formats DateOfBirth as "yyyy-MM-dd"
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        // Applying Display attribute to change the label as Date of Birth
        [Display(Name = "Date of Birth")]
        public DateTime DateOfBirth { get; set; }

        // Display "No Description Available" if null or empty
        [DisplayFormat(NullDisplayText = "No Description Available")]
        public string? JobDescription { get; set; }

        // Formats LastDateOfWorking as "MMM dd, yyyy" or displays "N/A" if null or empty
        [DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}", NullDisplayText = "N/A", ApplyFormatInEditMode = true)]
        // Applying DisplayName attribute to change the label as Last Date Of Working
        [DisplayName("Last Date Of Working")]
        public DateTime? LastDateOfWorking { get; set; }
    }
}

Run the application and navigate to Employee/Details. The employee details should be displayed with customized labels and formatted values defined by the data annotations.

Display and DisplayFormat Data Annotation Attributes in ASP.NET Core MVC Applications with Examples

Configuring Culture-Specific Formatting in ASP.NET Core MVC

Currency and date formats can vary based on cultural settings. We need to configure localization to ensure our application displays data according to specific cultures. 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 and the Great British pound. Let us proceed and understand how to implement Culture-Specific Formatting in our ASP.NET Core MVC Application:

Configuring Supported Cultures

First, define the cultures we want to support in the application. To do so, please modify the Program class as shown below. The following code is self-explained, so please read the comment lines for a better understanding.

using Microsoft.AspNetCore.Localization; // Namespace for localization middleware
using System.Globalization; // Namespace for culture-related information

namespace DisplayFormatDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Create a builder for setting up and configuring the web application.
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            // Registers MVC controllers with views support
            builder.Services.AddControllersWithViews();

            // Define the list of supported cultures
            // Define the list of supported cultures (locales) for the application.
            // Supported cultures are represented by CultureInfo objects
            // en-US (United States), en-GB (United Kingdom), and en-IN (India).
            var supportedCultures = new[]
            {
                new CultureInfo("en-US"), // English (United States)
                new CultureInfo("en-GB"), // English (United Kingdom)
                new CultureInfo("en-IN"), // English (India)
            };

            // Configure localization options for the application.
            // This includes setting the default culture, supported cultures, and how to detect the culture.

            builder.Services.Configure<RequestLocalizationOptions>(options =>
            {
                // Set the default request culture.
                // If no specific culture is provided by the user, the app will use "en-US" (US English).
                options.DefaultRequestCulture = new RequestCulture("en-US");

                // Specify the list of cultures supported by the app.
                // SupportedCultures specifies which cultures can be used to format data.
                options.SupportedCultures = supportedCultures;

                // Specify supported UI cultures.
                // SupportedUICultures defines the languages the application’s UI can support.
                options.SupportedUICultures = supportedCultures;
            });

            // Build the application based on the configured services
            var app = builder.Build();

            // Enable localization middleware to process requests based on the configured cultures
            // This middleware will check each request and apply the appropriate culture (language and formatting)
            // based on the settings provided in the localization configuration.
            app.UseRequestLocalization();

            //Check if the environment is not "Development".
            // If the app is not in development mode, it uses a custom error page and enforces HTTP Strict Transport Security (HSTS).
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error"); // Use a custom error page for exceptions.
                app.UseHsts(); // Enforces HTTPS for secure communication.
            }

            // Redirect HTTP requests to HTTPS
            app.UseHttpsRedirection(); // Enforces secure communication by redirecting HTTP to HTTPS.

            // Serve static files like CSS, JavaScript, and images from the "wwwroot" folder.
            app.UseStaticFiles(); // Enables serving static files.

            // Set up the routing system for the application.
            app.UseRouting(); // Defines how the app handles URLs and routes requests to the appropriate controllers and actions.

            // Enable authorization middleware (not configured in this example)
            app.UseAuthorization();

            // Define the default route for the MVC application.
            // This maps a URL pattern to a controller (Employee), an action (Details), and optionally an id parameter.
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Employee}/{action=Details}/{id?}");

            // Run the application and start listening for HTTP requests.
            app.Run(); // Starts the web server to handle incoming requests.
        }
    }
}
Creating the Culture View Model

In our view, we will add a dropdown list to allow users to select their preferred culture. First, create a ViewModel to hold the list of cultures and the selected culture. So, create a class file named CultureViewModel.cs within the Models folder and then copy and paste the following code:

using Microsoft.AspNetCore.Mvc.Rendering;

namespace DisplayFormatDemo.Models
{
    public class CultureViewModel
    {
        public string SelectedCulture { get; set; }
        public List<SelectListItem> Cultures { get; set; }
    }
}
Modifying the Employee Controller

We need to pass the list of cultures to the view. So, modify the Employee Controller as follows:

using DisplayFormatDemo.Models; 
using Microsoft.AspNetCore.Localization; 
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering; 
using System.Globalization; 

namespace DisplayFormatDemo.Controllers
{
    public class EmployeeController : Controller 
    {
        public IActionResult Details() 
        {
            // Hardcoded employee details for demonstration purposes.
            var employee = new Employee
            {
                Id = 1, 
                FullName = "Pranaya Rout", 
                Gender = "Male", 
                Age = 34, 
                DateOfJoining = new DateTime(2017, 1, 2), 
                DateOfBirth = new DateTime(1988, 2, 29), 
                EmailAddress = "pranaya.rout@example.com",
                Salary = 55000m, // m for decimal type
                PersonalWebsite = "https://dotnettutorials.net", 
                PerformanceRating = 4.5567, 
                JobDescription = string.Empty,
                LastDateOfWorking = null
            };

            // Creating a model for the culture selection dropdown.
            var cultureModel = new CultureViewModel
            {
                // The currently selected culture (from the request's culture).
                SelectedCulture = CultureInfo.CurrentCulture.Name, 

                // List of available cultures for the dropdown.
                Cultures = new List<SelectListItem>
                {
                    new SelectListItem { Value = "en-US", Text = "United States" }, // US English culture.
                    new SelectListItem { Value = "en-GB", Text = "United Kingdom" }, // UK English culture.
                    new SelectListItem { Value = "en-IN", Text = "India" }, // Indian English culture.
                }
            };

            // Passing the culture selection model to the view using ViewBag.
            ViewBag.CultureModel = cultureModel;

            // Returning the Employee model to the view to render the employee details.
            return View(employee);
        }

        // Action method for setting the selected culture.
        [HttpPost]
        public IActionResult SetCulture(string culture, string returnUrl) 
        {
            // Validate the culture string.
            // CultureInfo.GetCultureInfo ensures the culture string is a valid culture name (e.g., "en-US").
            culture = CultureInfo.GetCultureInfo(culture).Name;

            // Set the culture in a cookie.
            // Append a cookie that stores the selected culture information.
            // The cookie is named based on the default culture name.
            // MakeCookieValue sets the RequestCulture (the culture for both culture and UI culture).
            Response.Cookies.Append(

                // The name of the cookie that stores culture information.
                CookieRequestCultureProvider.DefaultCookieName,

                // The culture to store in the cookie.
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), 

                //Set the cookie's expiration date to 1 year from now.
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) } 
            );

            // Redirect the user back to the original URL after setting the culture.
            // LocalRedirect ensures that the redirection stays within the application for security purposes.
            return LocalRedirect(returnUrl);
        }
    }
}
Explanation:
  • We create a CultureViewModel instance with the list of cultures.
  • We store it in ViewBag.CultureModel to pass it to the view.
  • We add a new action, SetCulture, to handle the culture change request.
  • In SetCulture, we update the culture cookie with the selected culture.
Modifying the Details View

In the Details.cshtml view, we need to add the dropdown list and a form to change the culture. So, modify the Details.cshtml view as follows:

@model DisplayFormatDemo.Models.Employee

@{
    ViewData["Title"] = "Employee Details";
    var cultureModel = ViewBag.CultureModel as CultureViewModel;
}

<div class="container mt-5">

    <!-- Header Section -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>@ViewData["Title"]</h2>
        
        <!-- Culture Selection Form -->
        <form asp-action="SetCulture" asp-controller="Employee" method="post" class="form-inline">
            <label for="cultureSelect" class="mr-2 font-weight-bold">Select Culture:</label>
            <select id="cultureSelect" name="culture" class="custom-select" onchange="this.form.submit();">
                @foreach (var culture in cultureModel.Cultures)
                {
                    if (culture.Value == cultureModel.SelectedCulture)
                    {
                        <option value="@culture.Value" selected>@culture.Text</option>
                    }
                    else
                    {
                        <option value="@culture.Value">@culture.Text</option>
                    }
                }
            </select>

            <!-- Preserve the current URL to redirect after culture change -->
            <input type="hidden" name="returnUrl" value="@Url.Action("Details")" />
        </form>
    </div>

    <!-- Employee Details Card -->
    <div class="card shadow-sm">
        <div class="card-header bg-info text-white">
            <h5 class="mb-0">@ViewData["Title"]</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <tbody>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.Id)</th>
                            <td>@Html.DisplayFor(model => model.Id)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.FullName)</th>
                            <td>@Html.DisplayFor(model => model.FullName)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.Gender)</th>
                            <td>@Html.DisplayFor(model => model.Gender)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.Age)</th>
                            <td>@Html.DisplayFor(model => model.Age)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.DateOfJoining)</th>
                            <td>@Html.DisplayFor(model => model.DateOfJoining)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.LastDateOfWorking)</th>
                            <td>@Html.DisplayFor(model => model.LastDateOfWorking)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.EmailAddress)</th>
                            <td>@Html.DisplayFor(model => model.EmailAddress)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.Salary)</th>
                            <td>@Html.DisplayFor(model => model.Salary)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.PersonalWebsite)</th>
                            <td>
                                @if (!string.IsNullOrEmpty(Model.PersonalWebsite))
                                {
                                    <a href="@Model.PersonalWebsite" target="_blank">@Model.PersonalWebsite</a>
                                }
                                else
                                {
                                    @Html.DisplayFor(model => model.PersonalWebsite)
                                }
                            </td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.PerformanceRating)</th>
                            <td>@Html.DisplayFor(model => model.PerformanceRating)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.DateOfBirth)</th>
                            <td>@Html.DisplayFor(model => model.DateOfBirth)</td>
                        </tr>
                        <tr>
                            <th>@Html.DisplayNameFor(model => model.JobDescription)</th>
                            <td>@Html.DisplayFor(model => model.JobDescription)</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
Explanation:
  • We create a form that posts to SetCulture when the selected option changes.
  • The dropdown list is populated with cultures from cultureModel.Cultures.
  • The form includes a hidden field returnUrl to redirect back to the Details page after changing the culture.

When the user selects a different culture, the SetCulture action updates the culture cookie, which the application middleware uses to set the current culture for subsequent requests.

Testing the Application

Now, when you run the application:

  • Navigate to /Employee/Details.
  • You will see a dropdown list with “United States”, “United Kingdom”, and “India”.
  • Select a culture from the dropdown list.
  • The page will refresh, and the currency symbol and date formats should update according to the selected culture, as shown in the below image:

Configuring Culture-Specific Formatting in ASP.NET Core MVC

Benefits of using Display and DisplayFormat Attributes in ASP.NET Core MVC:

So, the DisplayFor and DisplayNameFor helpers in ASP.NET Core MVC, combined with Display and DisplayFormat attributes, offer a way to control how model data is presented in views:

  • Enhance Readability: Customize labels to be more user-friendly and descriptive.
  • Ensure Consistent Formatting: Apply uniform formats to dates, numbers, currencies, etc.
  • Handle Nulls: Provide default messages for null or empty fields to improve user experience.
  • Support Localization: Adapt data presentation to different cultural norms, enhancing global usability.

Note: The ApplyFormatInEditMode property of the DisplayFormat attribute specifies whether the formatting should be applied when the field is in edit mode (e.g., within a form input). If true, the format is applied even when editing; if false, the format is only used for display.

In the next article, I will discuss BindNever and BindRequired Attribute in ASP.NET Core MVC. In this article, I explain Display and DisplatFormat Data Annotation Attributes in the ASP.NET Core MVC application with examples. I hope you enjoy this article on Displaying and Formatting Data Annotation Attributes in the ASP.NET Core MVC.

Leave a Reply

Your email address will not be published. Required fields are marked *