http://www.codeproject.com/Articles/775220/ASP-Net-MVC-What-are-the-uses-of-Display-DisplayNa?utm_source=tuicool

In the last blog post on  ASP.Net MVC , we have discussed about implementing ListBoxes. You can read that article  here .
In this article we will go over different display attributes   in  ASP.Net MVC .

Let’s understand this with an example. We will be using tblEmployee table for this. The SQL scripts for creating  tblEmployee  table and inserting data into it are following:

Create table  tblEmployee 



Id  int primary key identity , 

FullName  nvarchar (100), 

Gender  nvarchar (10), 

Age  int , 

HireDate  DateTime , 

EmailAddress  nvarchar (100), 

Salary  int , 

PersonalWebSite  nvarchar (100) 

Insert into  tblEmployee  values 

( ‘George Thomas’, ‘Male’ , 37,  ’2014-02-03 16:50:47.788′, ‘GeorgeThomas@BestTEchnologyBlog.com’ , 40000, ‘www.BestTEchnologyBlog.com’ )

Insert into  tblEmployee  values 

( ‘Priyanka’ ,  NULL , 29,  ’2014-03-05 09:53:36.678′, ‘Priyanka@BestTEchnologyBlog.com’ , 36000, ‘www.BestTEchnologyBlog.com’ )

First of all, generate an ADO.NET Entity data model for the table  tblEmployee . You can refer here   to
know the steps to be followed to create an  ADO.NET Entity data model.

Then right click on the  Controllers  folder and add  HomeController .

Include the following  USING  statement to HomeController .

using  MVCDemo.Models;

Copy and paste the following code.

public class   HomeController  :  Controller 

{

 public  ActionResult  Details( int  id) 



SampleDBContext  db =  new  SampleDBContext (); 

tblEmployee  employee = db.tblEmployees.Single(x => x.Id == id); 

return  View(employee); 

}

}

Then right click on the  Details  action method and add  Details  view. Make sure that you are creating a strongly typed view against tblEmployee  class. Select Details  as the  Scaffold
template
 .

Set Aerial as our font – family by using a div tag.

Build the Solution and run it. We will get a screen like below.

But look at the output , it is not much pretty. There is no space in between Full andName and is displaying as FullName. Gender  is showing as blank. We have to make it much more pretty. The text should be Full
Name
 instead of FullName and ifGender is not specified, instead of showing blank there, a text of Gender not specified  should be appeared. How can we achieve this? Here comes the importance of display
attributes.

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 auto-generated tblEmployeeclass 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 Employee.cs class file.

Copy and paste the following code. Notice that I have tried to include the purpose of each attribute through the comments. Please read them carefully.

namespace  MVCDemo.Models 



    [ MetadataType ( typeof ( EmployeeMetaData ))] 

     public partial class   tblEmployee 

    { 

    }

     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  }")] 

        //[DisplayFormatAttribute(DataFormatString="{0  }")] 



        //To get time in 24 hour notation 

        //[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}")] 



        //To get time in 12 hour notation with AM PM 

        [ DisplayFormat (DataFormatString =  "{0:dd/MM/yyyy hh:mm:ss tt}" )] 

         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;  } 

    } 

}

Don’t forget to include following using statements:

using  System.ComponentModel.DataAnnotations; 

using  System.ComponentModel;

Now build the solution and run it. We can see a page like below.

Here everything is OK except the Salary. Even if we have used  [ ScaffoldColumn (false )] attribute for the Salary, it is still showing. I think you can guess the reason. In the comments itself, I have specified that  ScaffoldColumn  attribute
will work only when we use @Html.DisplayForModel() helper.

So instead of all the HTML in the View, we will get the same output by just adding one line of code which is shown below.

@Html.DisplayForModel()

This HTML helper will go through each property and will render the UI automatically.

Now let’s build the solution by pressing Ctrl+Shift+B  and refresh the page. We can see that the Salary is now hidden.

ASP.Net MVC – What are the uses of Display, DisplayName, DisplayFormat and ScaffoldColumn attributes的更多相关文章

  1. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库

    在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...

  2. 使用Visual Studio 2015 开发ASP.NET MVC 5 项目部署到Mono/Jexus

    最新的Mono 4.4已经支持运行asp.net mvc5项目,有的同学听了这句话就兴高采烈的拿起Visual Studio 2015创建了一个mvc 5的项目,然后部署到Mono上,浏览下发现一堆错 ...

  3. 一百元的智能家居——Asp.Net Mvc Api+讯飞语音+Android+Arduino

    大半夜的,先说些废话提提神 如今智能家居已经不再停留在概念阶段,高大上的科技公司都已经推出了自己的部分或全套的智能家居解决方案,不过就目前的现状而言,大多还停留在展厅阶段,还没有广泛的推广起来,有人说 ...

  4. Asp.net MVC 传递数据 从前台到后台,包括单个对象,多个对象,集合

    今天为大家分享下 Asp.net MVC 将数据从前台传递到后台的几种方式. 环境:VS2013,MVC5.0框架 1.基本数据类型 我们常见有传递 int, string, bool, double ...

  5. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第一章:创建基本的MVC Web站点

    在这一章中,我们将学习如何使用基架快速搭建和运行一个简单的Microsoft ASP.NET MVC Web站点.在我们马上投入学习和编码之前,我们首先了解一些有关ASP.NET MVC和Entity ...

  6. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之目录导航

    ASP.NET MVC with Entity Framework and CSS是2016年出版的一本比较新的.关于ASP.NET MVC.EF以及CSS技术的图书,我将尝试着翻译本书以供日后查阅. ...

  7. ASP.NET MVC开发:Web项目开发必备知识点

    最近加班加点完成一个Web项目,使用Asp.net MVC开发.很久以前接触的Asp.net开发还是Aspx形式,什么Razor引擎,什么MVC还是这次开发才明白,可以算是新手. 对新手而言,那进行A ...

  8. ASP.NET MVC原理

    仅此一文让你明白ASP.NET MVC原理   ASP.NET MVC由以下两个核心组成部分构成: 一个名为UrlRoutingModule的自定义HttpModule,用来解析Controller与 ...

  9. ASP.NET MVC——模型绑定

    这篇文章我们来讲讲模型绑定(Model Binding),其实在初步了解ASP.NET MVC之后,大家可能都会产生一个疑问,为什么URL片段最后会转换为例如int型或者其他类型的参数呢?这里就不得不 ...

随机推荐

  1. luogu2618 数字工程 DP

    题目大意:ACM实验室开启了一个数字工程项目,希望把正整数n通过一些特殊方法变成1.可采用的方法有:(1)减去1:(2)除以它的任意一个素因子. 每操作一次消耗一个单位的能量.问,把n变成1最少需要消 ...

  2. codetemplate

    <?xml version="1.0" encoding="UTF-8" standalone="no"?><templa ...

  3. 饭卡(hdoj--2546--背包)

    饭卡 Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submiss ...

  4. IPv6通讯原理(1) - 不能忽略的网卡启动过程

    本文主题:通过抓包分析,深入观察网卡启动过程的每个步骤,从而逐步掌握通讯原理.

  5. 45.Qt openGL实现三维绘图

    main.cpp #include <QApplication> #include <iostream> #include "tetraheadron.h" ...

  6. (C++)错误提示 c2352 :非静态成员函数的非法调用

    静态成员函数相当于全局函数,只是有一个类名字空间的限制.而类成员函数是成员内部的函数,同一个类的对象实例可以有很多,每一个实例都有自已不同的成员变量值,成员函数一般都是对成员自已的成员变量值在操作.所 ...

  7. C#泛型类的用途和说明

    class Program    {        public class Test<T, S>        {           //泛型类的类型参数可用于类成员          ...

  8. [hihocoder][Offer收割]编程练习赛43

    版本号排序 不知道什么傻逼原因,就是过不了 #pragma comment(linker, "/STACK:102400000,102400000") #include<st ...

  9. Win8.1应用开发之适配器模式(C#实现)

    实际上适配器模式是用于解耦.设想一下我们的程序模块A在与模块B打交道时,需要在许多地方多次使用B中某个类的方法,而负责开发B的程序猿Tom还未完全实现该类,会随时更改该类中的方法,那么当Tom在修改时 ...

  10. 运行于Windows内建账户下的服务访问映射网络驱动器的方法

    Windows服务如果是运行在本地系统帐户下或本地服务帐户下,它只能访问这个账户自己创建的映射驱动器,UNC路径访问则不受次限制. LocalService Account (NT AUTHORITY ...