2

Title kinda says it all.

There appears to be two ways to mark a field as "Please don't show on the UI" with attributes. One lives in the DataAnnotations namespace, which is where I think it belongs, and the other lives in the MVC-specific namespace System.Web.Mvc, which I think is the wrong place.

It means that for an MVC app, I have to dirty my domain class with the MVC namespace, rather than use the "more generic" ComponentModel.DataAnnotations.

Is there any way to have the MVC framework take notice of the Display() attribute?

Luke Puplett
  • 42,091
  • 47
  • 181
  • 266
Joe
  • 321
  • 3
  • 12

2 Answers2

4

You should be using ViewModels in the view, not Entities from your domain. Because the ViewModels (or commands) are view specific, it does not matter if they have a reference to System.Web.x.

I would look into SoC : http://en.wikipedia.org/wiki/Separation_of_concerns

And Automapper /W ViewModels : http://bengtbe.com/blog/2009/04/14/using-automapper-to-map-view-models-in-asp-net-mvc/

Also, to answer your quesion:

[HiddenInput(DisplayValue = false)] will render <input id="propId" name="propId" type="hidden" value="21" />

Display(AutoGenerateField=false)] will not render at all.

Paul
  • 12,392
  • 4
  • 48
  • 58
  • 3
    Hi Paul - thanks for the answer, but I am already using ViewModels in my views (and automapper :-)). With all due respect, I have to disagree that "it doesnt matter if they have a reference to ...". What I am aiming for is to re-use my view models in a silverlight project, so would much rather use the data annotations come from the "generic" assembly, rather than the MVC specific one. Maybe its a pipe dream to share the VMs, but if we buy into all this separation of concerns, and having a well defined UI/logic boundary, then it should be possible. Again, thanks. – Joe Sep 20 '11 at 09:06
2

Although you should really take note of Paul's answer re: using ViewModels, a common solution to your problem is to decorate your property with the UIHint attribute which lives in the System.ComponentModel.DataAnnotations namespace.

e.g.

[UIHint("Hidden")]

Then add a small view template in Shared\EditorTemplates\Hidden.cshtml like

@model object
@Html.HiddenFor( x => x)

Where the name of the template matches the string given in UIHint

StanK
  • 4,750
  • 2
  • 22
  • 46