Wednesday, May 30, 2012

ASP.NET MVC 3 - Effectively using Model metadata

In ASP.NET MVC 3, most developers might have observed the existence of the HTML helpers - DisplayForModel and EditorForModel. This post is just to give a hint on how effectively we can use the specified HTML helpers and hence we won't have any code Snippets here.

I frequently come across situations of creating proof of concept and several sample applications to evaluate certain implementations / metrics. In such cases, lot of time I really worried on creating a sample data entry / display page which consumes my time, because my core objective is to evaluate my target as early as possible. The EditorForModel HTML helper in ASP.NET MVC actually saves me lot of time and help me to just focus on my target while doing such POCs.

While doing so I thought some simple tweaks, like a way to represent display name, order ... for the property might help me to tune my sample page further. To achieve that, I got the help of DataAnnotations / Metadata.

Some sample requirements are
  • Need to hide a column - ScaffoldColumn(false)
  • Hidden value - HiddenInput
  • Display a different name - Display(Name = "Employee Name")
  • Display in a custom order - Display(Order=1)
  • Display format with different type than default - DataType(DataType.MultilineText)

Using these Metadata, we can, hide a property from creating HTML elements for that, create a hidden value element for a property, display a different name than that of the property, display in a custom order we need, specify what type of HTML element and what format can be used, etc.

Once you start explore other parameters of attributes and options, you can achieve lot of cases with minimal effort. Really its a time saving mechanism. If none of the options fits our scenario, then we can do the regular way.   
Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.