Recently I was asked about a strange problem concerning the Display attribute in ASP.NET MVC 2. The problem was the Display atribute had no effect in the view. It was really a strange one. I tried it myself and it was true.
Let’s have a look at that situation. Below is the model for a user.
1 2 3 4 5 6 7 8 9 |
public class User { [ScaffoldColumn(false)] public int Id { get; set; } [Required] [Display(Name = "User name")] public string Name { get; set; } } |
Using Html.DisplayForModel() in our view results in the following web page:
As you can see the Display attribute has not been taken into consideration at all. The reason for this is ASP.NET MVC 2 RTN do not know about it. Display attribute is new for .NET 4 and ASP.NET MVC 2 RTM is compiled under .NET 3.5. This attribute is supported in Futures release of ASP.NET MVC and will be supported in any newer releases (like MVC 3).
OK, but I didn’t give you a working solution so far. Well, there is – DisplayName attribute. Note that it resides in System.ComponentModel not in System.ComponentModel.DataAnnotations. Our model now looks like this:
1 2 3 4 5 6 7 |
public class User { ... [Required] [DisplayName("User name")] public string Name { get; set; } } |