0

I have the following in my EntityFramework Domain Models:

[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }

[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }

And in My view I do the following:

@Html.LabelFor(model => model.FirstName)

But I was wondering, why is it preferred to specify the "Display Name" in my model instead of just writing the Label manually in the View page?

I can actually see this causing more problems, what if in 6 months time someone comes to me and says "We don't want it to say First Name anymore, we want it to say "Your First Name" I would either have to revert to hard coding it in my view or recompile my Model Project for the change to take effect..

Is there any benefits I am not aware of for using data annotations?

tornup
  • 263
  • 1
  • 4
  • 15
  • I'm going to say this. I've got an ASP.NET MVC project that's 2 years old. I'm actually regretting using the Data Annotations. Every time we find so much as a spelling mistake we've got to recompile the site. Given that for love nor money I can get the combination of EF/ASP.NET's cold start time down to less than 30 seconds this is a complete pain in the bum! – Chris Nevill Jun 16 '15 at 14:36

2 Answers2

4

The benefit of DisplayAttribute is localization like the code below.

[Required]
[Display(Name = "First Name", ResourceType = typeof(YourResources)))]
public string FirstName { get; set; }

ASP.NET MVC 3 localization with DisplayAttribute and custom resource provider has some good answers about localization and different way to achieve it.

Community
  • 1
  • 1
Ekk
  • 5,627
  • 19
  • 27
3

The benefit is simply DRY.

So you currently use it in a single place, your edit page. Now add:

  • multiple validation messages (First Name is required etc)
  • a view (read-only) page
  • a list page
  • a summary / tooltip
  • a reference on another page
  • logging/tracing
  • a breadcrumb (okay, pushing it a bit here)

now you have to change it in 15+ places, chances of missing one... high
[chances of a typo in one or more of those... not low]

So in each of those you use reference the DisplayName rather than typing it in manually... now you only have to change it in... 1 place.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57