Attributes in ASP.NET MVC (Part 1)

Attributes in ASP.NET MVC Application

In this article, I am going to discuss built-in Attributes in ASP.NET MVC Application. Please read our previous article where we discussed Creating Custom HTML Helpers in ASP.NET MVC Application. The ASP.NET MVC Framework provides many built-in attributes that can be applied to the Model or its properties. I divided this article into two parts. In this article, we are going to discuss the following attributes.

  1. Display
  2. DisplayName
  3. DisplayFormat
  4. ScaffoldColumn
  5. DataTypeAttribute
  6. DisplayColumnAttribute 

And in the next article, I am going to discuss the following attribute.

  1. UIHint
  2. HiddenInput
  3. ReadOnly
Creating the Database Table:

We are going to use the following Employee table.

Attributes in ASP.NET MVC Application

Please use below SQL Script to create and populate the Employee table that we are going to use in this article.

-- Create Employee Table
Create table Employee
(
  Id int primary key identity,
  FullName nvarchar(100),
  Gender nvarchar(10),
  Age int,
  HireDate DateTime,
  EmailAddress nvarchar(100),
  Salary int,
  PersonalWebSite nvarchar(100)
) 
GO
  
-- Insert some test data into Employee Table
Insert into Employee values
('Pranaya Rout', 'Male', 29, '2017-01-02 17:53:46.833', 'info@dotnettutorials.net', 55000, 'https://dotnettutorials.net/')
Insert into Employee values
('Anurag Mohanty', NULL, 28, '2015-05-02 19:43:25.965', 'info@dotnettutorials.net', 45000,'https://dotnettutorials.net/')
Insert into Employee values
('Priyanka Dewangan', 'Female', 27, '2016-05-02 19:43:25.965', 'info@dotnettutorials.net', 50000,'https://dotnettutorials.net/')
GO
Create an empty ASP.NET MVC application:

Create an empty ASP.NET MVC Project with the name AttributesInMVC. Generate the ADO.NET Entity Data model for table Employee using the database first approach. Save and build the project. It will create the following Employee Model

namespace AttributesInMVC.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class Employee
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Gender { get; set; }
        public Nullable<int> Age { get; set; }
        public Nullable<System.DateTime> HireDate { get; set; }
        public string EmailAddress { get; set; }
        public Nullable<int> Salary { get; set; }
        public string PersonalWebSite { get; set; }
    }
}
Creating Employee Controller:

Right-click on the “Controllers” folder and add a controller with the name “EmployeeController” and then copy and paste the following code in it.

using AttributesInMVC.Models;
namespace AttributesInMVC.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Details(int id)
        {
            EmployeeDBContext dbContext = new EmployeeDBContext();
            Employee employee = dbContext.Employees.Single(x => x.Id == id);
            return View(employee);
        }
    }
}
Creating Details View:

Add the details view and then copy and paste the below code in it.

@model AttributesInMVC.Models.Employee
@{
    ViewBag.Title = "Details";
}

<div>
    <h4>Employee Details</h4>
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.FullName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.FullName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Gender)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Gender)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Age)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Age)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.HireDate)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.HireDate)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmailAddress)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmailAddress)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Salary)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Salary)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.PersonalWebSite)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.PersonalWebSite)
        </dd>
    </dl>
</div>

Now, run the application and navigate to the URL http://localhost:61449/Employee/Details/1 and It will display the employee information as shown below.

Without Attributes in ASP.NET MVC Application

Notice that the output is not that pretty. We can control the display of data in a view using display attributes that are found in the System.ComponentModel.DataAnnotations namespace.

It is not a good idea to add display attributes to the properties of the auto-generated “Employee” class as our changes will be lost if the class is auto-generated again.

Creating Employee Partial Class:

We need to create a partial “Employee” class and we need to decorate that class with the display attributes.  So, Right-click on the “Models” folder and then add a class file with the name ModifyEmployee.cs. Once you created the ModifyEmployee.cs then copy and paste the following code in it. The code is self-explained. So, please go through the comment lines.

namespace AttributesInMVC.Models
{
    [MetadataType(typeof(EmployeeMetaData))]
    public partial class Employee
    {
    }

    public class EmployeeMetaData
    {
        //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; }

        //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}")]
        // public DateTime? HireDate { get; set; }

        // Display only Time Part
        // [DataType(DataType.Time)]
        // Display only Date Part
        [DataType(DataType.Date)]
        public DateTime? HireDate { get; set; }

        // If gender is NULL, "Gender not specified" text will be displayed.
        [DisplayFormat(NullDisplayText = "Gender not specified")]
        public string Gender { get; set; }

        //If you don't want to display a column use ScaffoldColumn attribute.
        //This only works when you use @Html.DisplayForModel() helper
        //[ScaffoldColumn(false)]
        //public int? Salary { get; set; }

        // Display currency symbol. For country specific currency, set culture using globalization element in 
        //web.config.  For Great Britain Pound symbol<globalization culture="en-gb"/>
        [DataType(DataType.Currency)]
        public int? Salary { get; set; }

        // Display mailto hyperlink
        [DataType(DataType.EmailAddress)]
        public string EmailAddress { get; set; }

        // Generate a hyperlink
        [DataType(DataType.Url)]
        public string PersonalWebSite { get; set; }
    }
}

Make sure to include the following using statements:

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

Now Run the application and see the output as shown below.

Using Attributes in ASP.NET MVC Application

The DisplayColumn attribute is useful when a class has a property of the complex type, and we want to pick only one property of that complex object for display purposes.

Let’s understand this with an example.

Right-click on the “Models” folder and add a class file with the name Company.cs and then copy and paste the below code. 

namespace AttributesInMVC.Models
{
    public class Company
    {
        public Employee CompanyDirector
        {
            get
            {
                EmployeeDBContext dbContext = new EmployeeDBContext();
                return dbContext.Employees.Single(x => x.Id == 1);
            }
        }
    }
}

Notice that, this class has CompanyDirector property which returns an Employee object. The employee is a complex type so; Employee object has got several properties. If we want FullName to be used for display purposes, then make the following changes.

Modifying the ModifyEmployee.cs

Modify the ModifyEmployee.cs file as shown below where we decorate the “Employee” partial class with DisplayColumn attribute.

namespace AttributesInMVC.Models
{
    [MetadataType(typeof(EmployeeMetaData))]
    [DisplayColumn("FullName")]
    public partial class Employee
    {
    }

    public class EmployeeMetaData
    {
        [DisplayName("Full Name")]
        public string FullName { get; set; }

        [DataType(DataType.Date)]
        public DateTime? HireDate { get; set; }
        
        [DisplayFormat(NullDisplayText = "Gender not specified")]
        public string Gender { get; set; }
        
        [DataType(DataType.Currency)]
        public int? Salary { get; set; }
        
        [DataType(DataType.EmailAddress)]
        public string EmailAddress { get; set; }
        
        [DataType(DataType.Url)]
        public string PersonalWebSite { get; set; }
    }
}
Change the “Details” action method in the “Employee” controller class as shown below.
namespace AttributesInMVC.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Details()
        {
            Company company = new Company();
            return View(company);
        }
    }
}
Copy and paste the following code in Details.cshtml view
@model AttributesInMVC.Models.Company
@{
    ViewBag.Title = "Details";
}
@Html.DisplayTextFor(x => x.CompanyDirector)

Navigate to http://localhost:61449/Employee/Details and you should see the FullName of the employee. 

In the next article, I will continue our discussion regarding Attributes in MVC application. Here, in this article, I try to explain Attributes in MVC application to format the data with real-time examples. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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