Attributes in MVC (Part 1)

Attributes in MVC (Part 1)

There are many attributes available in MVC that can be applied to ASP.NET MVC model or its properties. We will discuss attributes in MVC in this article as well as in the next article. So I divided this article into two parts.

In this part, we will discuss the following attributes, with examples. 

1. Display

2. DisplayName

3. DisplayFormat

4. ScaffoldColumn

5. DataTypeAttribute, 

6. DisplayColumnAttribute  

And in the next article, I will discuss the following attribute

7. UIHint

8. HiddenInput

9. ReadOnly

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
Fetch the records:

Select * From Employee

attributes in MVC

Let’s create an empty ASP.NET MVC application with the name AttributesInMVC.

Generate ADO.NET entity data model for table Employee. 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; }
    }
}
Right click on the “Controllers” folder and add a controller with the name “EmployeeController” and copy and paste the below code.
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);
        }
    }
}
Add the details view and copy and paste the below code.
@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>

Run the application and navigate to the following URL

http://localhost:61449/Employee/Details/1

It will display the following output.

attributes in MVC

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 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.

So let’s create another partial “Employee” class and decorate that class with the display attributes.  Right click on the “Models” folder and add ModifyEmployee.cs class file. Copy and paste the following code.

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

attributes in MVC

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 purpose.

Let’s understand this with an example.

Right-click on the “Models” folder and add a class file with the name Company.cs and 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 purpose, then make the following changes.

Modify the ModifyEmployee.cs file as shown below where we decorate “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 “Details” action method in “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, we will continue our discussion regarding Attributes in MVC application.

SUMMARY:

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 need. 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 *