Using Display/DisplayName attributes in MVC

Introduction

In this article I will post a small example of using Display and DisplayName attribute. Today when I saw a junior developer struggling with DisplayName attribute I thought it to blog it for others also.

What is Display/DisplayName Attribute?

It defines the text we want to show on UI as form fields and Validation Messages.

Why we need Display/DisplayName Attribute?

We will discuss this with an example. Lets assume we have a model with two properties FirstName and ListBoxValue.

public class Employee
{
public string FirstName { get; set; }
public string ListBoxValue { get; set; }
}

This is how our view looks like:

razorview

Now when this model will be rendered on the view as seen below, looks a bit ugly and unformated.

View

For such scenarios only we have two built in attributes: Display and DisplayName. Using these attributes we can control how the text is rendered on the view. As we can see in the below code snippet, I have added Display Attribute on property named “FirstName” and DisplayName attribute on property named ListBoxValue with the text which I want to be rendered on the view in place of property names.

public class Employee
{
[Display(Name = “First Name”)]
public string FirstName { get; set; }
[DisplayName(“List Box Value”)]
public string ListBoxValue { get; set; }
}

After applying the attributes to our property this is how our View is rendered, which looks good.

changedview

Suppose, If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

public class BaseViewModel
{
[Display(Name = “Basic Name”)]
public virtual string FirstName { get; set; }
}

public class Employee : BaseViewModel
{
[Display(Name = “First Name”)]
public string FirstName;
[DisplayName(“List Box Value”)]
public string ListBoxValue { get; set; }
}

 Difference between Display and DisplayName

Display attribute should be preferred over DisplayName attribute. The former one comes form DataAnnotations namespace and exposes more properties than the later one, ie. ShortName, Prompt, GroupName, Order, Description, which are used by DataAnnotationsMetadataProvider.

Most importantly, DisplayName accepts only literals, while Display accepts resource type and key, which can be used to provide translations using separate resource files (resx).

Point to remember

The correct way of using DisplayName is on properties with getters and setters because by design MVC Binding applies to properties, not fields.

[Display(Name = “First Name”)]
public string FirstName;

Hope this helps.

Advertisements

Select only one checkbox

Today I will detail a situation faced by one of my friend. I would call it a software design disaster, how? I will explain. He has to develop a page with two grids similar to below image. Capture

The functionality required was very unorthodox. In the grid (captioned Vertically), the user should be allowed to select only one Checkbox per year and in second grid (captioned Horizontally), the user should be allowed to select only one Checkbox per criteria/per row. Although both these situations could have been handled by using Radio Buttons, but he was adamant that he want it to be a Checkbox only, to which i suggested him to use radio button and by using CSS make it look like a Checkbox. But he wanted it to be a Checkbox only.

For him i wrote a JQuery function to get the desired results, which i am sharing.

$(document).ready(function () {
$(‘:checkbox’).on(‘change’,function(){
var th = $(this),
name = th.attr(‘name’);
if(th.is(‘:checked’)){
$(‘:checkbox[name=”‘ + name + ‘”]’).not(th).prop(‘checked’,false);
}
});
});

The above function is very simple and works on name attribute. On click of a Checkbox it UnSelect all Checkboxes with the same name except the current Checkbox.

jquery

Dynamic query for Parent/Child

Often new developers gets tasks to create dynamic menus from database and the first thing they stuck is how to query the data from database.  I am not writing anything new; its just I want to write assuming it will help somebody someday.

To begin with I will create a new SQL Table first. The below table consists of four columns:

  1. MenuId
  2. MenuName
  3. Description
  4. ParentId

GO

/****** Object: Table [dbo].[tblMenu] Script Date: 03/09/2016 11:18:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tblMenu](
[MenuID] [int] IDENTITY(1,1) NOT NULL,
[MenuName] [varchar](50) NULL,
[Description] [varchar](255) NULL,
[ParentID] [int] NULL,
CONSTRAINT [PK_Menu] PRIMARY KEY CLUSTERED
(
[MenuID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

I inserted somesample data using below query.

INSERT INTO [tblMenu]
Select ‘Product’,’A List of Products’, NULL
UNION ALL Select ‘Applications’,’Appliations’,NULL
UNION ALL Select ‘Document’,’Documentation’, NULL
UNION ALL Select ‘Support’,’Support’, NULL
UNION ALL Select ‘Download’,’Download’, NULL
UNION ALL Select ‘Background’,’ProductBackground’, 1
UNION ALL Select ‘Details’,’Product Details’, 1
UNION ALL Select ‘Mobile Device’,’Mobile DeviceApplications’, 2
UNION ALL Select ‘Portal’,’Portal Applications’,2
UNION ALL Select ‘Web Applicaitons’,’WebApplications’, 2
UNION ALL Select ‘Demo’,’Demo Applicaitons’, 2
UNION ALL Select ‘Performance Tests’,’ApplicationPerformance Tests’, 2
UNION ALL Select ‘Tutorials’,’TutorialDocumentation’, 3
UNION ALL Select ‘Programmers’,’ProgrammDocumentation’, 3
UNION ALL Select ‘FAQ’,’Frequently AskedQuestions’, 4
UNION ALL Select ‘Forum’,’Forum’, 4
UNION ALL Select ‘Contact Us’,’Contact Us’, 4
UNION ALL Select ‘InternetRestrictions’,’Internet Restrictions’, 6
UNION ALL Select ‘Speed Solution’,’Speed Solutions’,6
UNION ALL Select ‘Application Center Test’,’Application Center Test Results’, 12
UNION ALL Select ‘Modem Results’,’Modem Results’,12

After inserting the data this is how my data looks like

Sql Data

Then the final query to get the desired output.

SELECT
parent.MenuId ParentId,
parent.MenuName Menu,
child.MenuId ChildId,
child.MenuName as SubMenu
FROM dbo.tblMenu parent
INNER JOIN tblMenu child ON parent.MenuId = child.ParentId;

This is how data looks now.

final query

Hope it will help somebody.