Useful Attributes of MVC: Part 1

The following are the attributes that we will discuss in this article.

  1. DisplayName
  2. DisplayFormat
  3. DataType
  4. UiHint

For the demo, we will use the following database table records.



The following is a code snippet for creating the table.
  1. CREATE DATABASE db_Attibutes;  
  2. GO  
  3. USE db_Attibutes;  
  4.   
  5. CREATE TABLE tblAttibute  
  6.   
  7. (  
  8.   Id INT IDENTITY PRIMARY KEY,  
  9.   EmployeeName NVARCHAR(150),  
  10.   Gender NVARCHAR(10),   
  11.   HireDate DATETIME,  
  12.   EmailAddress NVARCHAR(100),  
  13.   Salary INT,  
  14.   PersonalBlog NVARCHAR(200)  
  15. );  
  16.   
  17. INSERT INTO tblAttibute VALUES  
  18.   ('AidenPearce','Male','2013-07-20','[email protected]',32000,'www.aiden.com'),  
  19. ('Lara Croft','Female','2012-12-11','[email protected]',37000,'www.lara.com'),  
  20. ('Max Payne',null,'2011-11-01','[email protected]',40000,'www.max.com'

Step 1

Open Visual Studio and create a new MVC 4 project.

 
 
Select an Empty template.
 
 

Step 2
 
Go to Tools -> NuGet Package Manager -> Manage NuGet Packages for solution…
 
 
 
Install Entity Framework.
 


Step 3
 
Right-click on the Models folder and add two class files.

In Employeee.cs add the following.

  1. using System;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4. namespace AttributesInMVC.Models  
  5.  {  
  6.     [Table("tblAttibute")]  
  7.        public class Employee   
  8. {  
  9.    public int Id { getset; }  
  10.    public string EmployeeName { getset; }  
  11.    public string Gender { getset; }  
  12.    public Nullable<DateTime> HireDate { getset; }   
  13.    public string EmailAddress { getset; }  
  14.    public int Salary { getset; }  
  15.    public string PersonalBlog { getset; }  
  16.   
  17. }  

In EmployeeDB.cs add the following.

  1. using System.Data.Entity;  
  2.   
  3. namespace AttributesInMVC.Models  
  4. {  
  5.    public class EmployeeDB: DbContext  
  6.   {  
  7.    public DbSet<Employee> Employees { getset; }  
  8.   }  

Build the solution.

Note: To learn more about DbContext and DbSet click here.

Step 4
 
Add a connection string in the root web.config file.
  1. </entityFramework>  
  2.    <connectionStrings>  
  3.   
  4.        <add name="EmployeeDB" connectionString="server=.;database=db_Attibutes;Integrated Security=SSPI"providerName="System.Data.SqlClient" />  
  5.   
  6.    </connectionStrings>  
  7. </configuration> 

Step 5

Add a controller.

 

Step 6
 
Create an instance of the EmployeeDB class in the Index action method but be sure to include the namespace where this EmployeeDB class is present.
  1. using AttributesInMVC.Models;  
  2.   
  3.  public ActionResult Index()   
  4.  {  
  5.     EmployeeDB employeeDB = new EmployeeDB();  
  6.     List<Employee> employee = employeeDB.Employees.ToList();  
  7.     return View(employee);  
  8.  } 

In the Index method, all we are doing is creating an instance of the EmployeeDB class. This EmployeeDB class has the property “Employees” that will return a DbSet of employees from the database table.

Step 7
 
Add an Index view.
  1. Select the Model class as Employee
  2. Choose the scaffold template as List


Some auto-generated codes will be added in the Index view.

 
 

Provide a table border of 1 and use style to collapse the border.
  1. <table border="1" style="border-collapse:collapse"> 

Run the application.


Now let's see how to use attributes.

In the output above, look at the column headings. Let's say we want a space between EmployeeName, EmailAddress and PersonalBlog. For that we can use the Display attribute.

DisplayAttribute or Display or DisplayName attribute: DisplayAttribute and Display is present in the System.ComponentModel.DataAnnotations namespace.

The DisplayName is present in the System.ComponentModel namespace.

Flip to the Employee model class and write the following just above the EmployeeName property.

 

This Display attribute expects a named parameter and here we want to change the display name of the property from EmployeeName to Employee Name.
  1. Display(Name="Employee Name")]  
  2. public string EmployeeName { getset; } 

Build and run the application.

 
So, there is white space between Employee and Name.

Now just like that change the display name for HireDate, EmailAddress and PersonalBlog.
  1. using System;  
  2. using System.ComponentModel;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5.   
  6. namespace AttributesInMVC.Models  
  7.  {  
  8.        [Table("tblAttibute")]  
  9.           public class Employee  
  10.                 {  
  11.                     public int Id { getset; }  
  12.                   [Display(Name = "Employee Name")]  
  13.   
  14.                    public string EmployeeName { getset; }   
  15.   
  16.                    public string Gender { getset; }  
  17.                    [DisplayName("Hire Date")]  
  18.   
  19.                   public Nullable<DateTime> HireDate { getset; }  
  20.                   [DisplayAttribute(Name = "Email Address")]  
  21.   
  22.                   public string EmailAddress { getset; }  
  23.   
  24.                   public int Salary { getset; }  
  25.                  [Display(Name = "Personal Blog")]  
  26.   
  27.                  public string PersonalBlog { getset; }  
  28.   
  29.              }  

DisplayFormat attribute: In the following output look at the gender of the employee Max Payne. It is blank.
 

Let's suppose for some reason we don't want an empty or a null field and we want to replace it with text. For that we can use a a DisplayFormat attribute.

Pass a value for NullDisplayText parameter of DisplayFormat attribute.
 
 
  1. [DisplayFormat(NullDisplayText="No Gender")]  
  2. public string Gender { getset; } 

Build and run the application.

 
 
So, the gender of empty is not null any more. Now let's suppose for some reason we don't want to display the Hire time with date and for that all we need to do is change the DateFormatString of HireDate using DisplayFormat attribute.
  
Build and run the application.
 
 
So, now the HireDate displays only the date part.

Now look at the Email Address and Personal Blog column, these are displayed as simple text. Let's say for some reason we want to display an Email Address as a mailto link and Personal Blog as a URL. For that we can use a DataType attribute.

DataType Attribute: The DataType attribute is in the System.ComponentModel.DataAnnotations namespace.



This DataType expects an enum. Select the type as Email Address.
  1. [DisplayAttribute(Name = "Email Address")]  
  2. [DataType(DataType.EmailAddress)]  
  3. public string EmailAddress { getset; } 

Select the data type as URL for PersonalBlog property as in the following:

  1. [DataType(DataType.Url)]  
  2. [Display(Name = "Personal Blog")]  
  3. public string PersonalBlog { getset; } 

Build and run the application.



If we click on any of the Email Addresses, we will get mail in the window where we can specify the way in which we want to open the link.
 


Look at the salary column. Let's say we want to display the currency with the salary. For that we can set the DatatType to Currency.
  1. [DataType(DataType.Currency)]  
  2. public int Salary { getset; } 

Build and run the application.



The currency value is displayed as dollars.

Let's say we want to display the salary in a country specific currency like Rupees. For that set the globalization culture to en-in under the System.Web in the web.config file.
  1. <system.web>  
  2. <globalization culture="en-in"/> 

Run the application.

 
UIHint attribute: The UIHint attribute is used to specify a display template that can be used to display the data fields.

In our Index view, whenever we click any of the personal blog URLs, it opens in the same page.
 

Click on any URL.



Let's say our business requirement is such that we want to open it in a new window and for that we need to make some changes.

The first thing we need to do is, add a Shared folder in Views.
 

The next thing is, we need to add a DisplayTemplates folder inside the Shared folder.
 

Inside this DisplayTemplates folder add a view.
 

NOTE

The view name must match the URL DataType attribute.

Now add the following in URL view.
  1. <a href="@ViewData.Model" target="_blank">@ViewData.Model</a> 
  1. The @ViewData.Model will provide us the href.
  2. Set the target to _blank.
  3. @ViewData.Model will provide us the name for the URL.

Build and run the application.

Open any Personal Blog.
 


So, now the page will open in a new window.

How it works

Whenever we decorate any property with an enum as a DataType, it will check if there is a DisplayTemplate with a same name, a URL. It will look at the display template in the DisplayTemplates folder and this folder can be inside the Shared folder or in the Home folder. But if we add templates inside the Shared folder then it can be accessed by the entire application.

Now look at the way we decorated this URL, it will open all the URLs in a new window and let's say our requirement is to only open this Personal Blog link in a new window. For that we need to make some changes.

First change the URL view from URL to Blog or something else.

 
Flip to Employee.cs in the Models folder and decorate the PersonalBlog property with the UIHint attribute and inside this UIHint pass the DisplayTempate, “Blog”.
  1. [UIHint("Blog")]  
  2. [DataType(DataType.Url)]  
  3. [Display(Name = "Personal Blog")]  
  4. public string PersonalBlog { getset; } 

Download the source code from here.

Summary

In this article we learned four useful attributes that we can use in our MVC applications.

I hope you like it. Thank you.

Up Next
    Ebook Download
    View all
    Learn
    View all