DisplayName
Attribute:
The DisplayName
attribute is used to specify the display name of a model property. It is typically used in conjunction with the EditorFor
and DisplayFor
HTML helpers to render the property name in the UI. The DisplayName
attribute can be applied to either a property or a class, and it can take a single argument, which is the display name of the property. Here’s an example:
In this example, the DisplayName
attribute is used to specify the display names of the FirstName
and LastName
properties of the Customer
class. When the EditorFor
or DisplayFor
HTML helpers are used to render the properties, they will display the specified display names (“First Name” and “Last Name”) instead of the property names (“FirstName” and “LastName”).
Display
Attribute:
The Display
attribute is used to specify various metadata about a model property, including the display name, the order in which the property should be displayed, and the format in which it should be displayed. The Display
attribute can be applied to either a property or a class, and it takes several arguments that can be used to specify different metadata. Here’s an example:
In this example, the Display
attribute is used to specify the display names and the order of the FirstName
and LastName
properties of the Customer
class. The Name
argument is used to specify the display name, and the Order
argument is used to specify the order in which the properties should be displayed. When the EditorFor
or DisplayFor
HTML helpers are used to render the properties, they will display the specified display names (“First Name” and “Last Name”) in the specified order (1 and 2).
Differences between DisplayName
and Display
Attributes:
The main difference between the DisplayName
and Display
attributes is that the DisplayName
attribute is used only to specify the display name of a model property, whereas the Display
attribute can be used to specify various metadata, including the display name, the order, and the format. Additionally, the DisplayName
attribute can take only a single argument, which is the display name, whereas the Display
attribute can take multiple arguments that can be used to specify different metadata.
Both the DisplayName
and Display
attributes are useful in ASP.NET MVC for specifying the display name of a model property. However, the Display
attribute provides more flexibility by allowing you to specify various metadata, including the display name, the order, and the format. The choice between the two attributes will depend on your specific requirements and the level of metadata that you need to specify.