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. 使用register_chrdev注册字符设备

    1.2.2  使用register_chrdev注册字符设备 注册字符设备可以使用register_chrdev函数. int register_chrdev (unsigned int major, ...

  2. C语言 - .c和.h文件的困惑

    本质上没有任何区别. 只不过一般:.h文件是头文件,内含函数声明.宏定义.结构体定义等内容. .c文件是程序文件,内含函数实现,变量定义等内容.而且是什么后缀也没有关系,只不过编译器会默认对某些后缀的 ...

  3. JS轮播图动态渲染四种方法

    一. 获取轮播图数据  ajax 二.根据数据动态渲染 (根据当前设备 屏幕宽度判断) 1. 准备数据 2. 把数据转换成html格式的字符串 动态创建元素 字符串拼接 模板引擎 框架方法 2.把字符 ...

  4. typescript 基本数据类型

    1.boolen 布尔类型 let boolen1: boolen = false; 2.number 数字类型 let num1: number = 0b110;//二进制 let num2: nu ...

  5. Java中Calendar(日历)相关API举例

    Java中Calendar(日历)相关API举例,实现功能:输入一个年份和月份打印出这个月的日历. package calendarPrint; import java.util.Calendar; ...

  6. Irrlicht 1.8.4 + Win7 + VC2015 + x64 +OpenGL编译

    1. 下载irrlicht1.8.4 https://nchc.dl.sourceforge.net/project/irrlicht/Irrlicht%20SDK/1.8/1.8.4/irrlich ...

  7. Selenium的文件上传JAVA脚本

    在写文件上传脚本的时候,遇到了很多问题,包括元素定位,以及上传操作,现在总结下来以下几点: 1. 上传的控件定位要准确,必要时要进行等待 WebElement adFileUpload = drive ...

  8. fastJson解析复杂对象时碰到的问题

    碰到map对象无法解析出来,发现问题是缺少有get/set方法,否则无法解析. 对象转json字符串 JSON.toJSONString(module) json字符串转对象(必须是pojo) mod ...

  9. pc端和移动端的轮播图实现(只是结构,内容以后慢慢补充)

    轮播图 PC端 移动端 原生js的写法 图片顺序 8123456781 设置计时器 当过度完成之后判断index是否到达两边界限,是的话设置位移 手指touchstart时,获取位置,暂停计时器 手指 ...

  10. Windows 下修改 MySQL 编码为 utf8

    问题 Windows 下安装 MySQL 后,默认编码不全utf8. mysql> show variables like '%char%'; +------------------------ ...