Loading

ASP.NET MVC

What is Attributes in ASP.NET MVC?. The Complete ASP.NET MVC Developer Course 2023 [Videos].

In this article, I am going to discuss Built-in Attributes in ASP.NET MVC applications. Please read our previous article where we discussed Creating Custom HTML Helpers in ASP.NET MVC applications. 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 Video, 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 Video.

-- 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
Create an empty ASP.NET MVC application:






Create an empty ASP.NET MVC Project with the name AttributesInMVCGenerate 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 dont 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.

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

See All

Comments (296 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET MVC / Youtube

What is MVC?

MVC is an architectural software design pattern that is used for developing interactive applications where their user interaction is involved and based on the user interaction some event handling has occurred. It is not only used for web-based applications but it can also be used for Desktop or mobile-based applications where there are user interactions involved.
28-jan-2022 /28 /296

ASP.NET MVC / Youtube

How to Creat First ASP.NET MVC Application using Visual Studio?

In this article, I am going to discuss how to create the first ASP.NET MVC Application step by step from scratch using Visual Studio 2015. You can use any version as per your choice but the step will remain the same. Please read our previous article before proceeding to this article where we gave a brief introduction to ASP.NET MVC Framework.
28-jan-2022 /28 /296

ASP.NET MVC / Youtube

What is ASP.NET MVC File and Folder Structure?

In this article, I am going to discuss the auto-generated ASP.NET MVC File and File Structure when we create a new ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed how to create ASP.NET MVC 5 application step by step from scratch.
28-jan-2022 /28 /296